/**
 * 商品操作
 * Last Update:2012-12-28
 */
ec.pkg("ec.product");
ec.load("ajax");
ec.load("ec.box", {
  loadType: "lazy"
});
ec.load("ec.index");
ec.load("cloud-zoom", function () {
  setTimeout(function () {
    $("#product-img").CloudZoom();
  }, 200);
});
ec.load("ec.product.gift");
ec.load("ec.product.coupon");

ec.load("rush");
ec.load("deposit");


ec.load("jquery.fixed", function () {
  $(function () {
    $("#pro-tab-all").fixed();
  });
});

_paq.push(['trackLink', '详情页', 'link', ' ']);
ec.code.addAnalytics({
  hicloud: true
});

//倒计时
ec.ui.countdown2 = function (selector, options) {
  var obj = $(selector),
    timer = obj.data("countdown"),
    timeIndex = 0,
    //当前倒数目标时间
    preTarget,

    //options = $.extend({}, options),
    diff,
    diffMs = options.now.getTime() - new Date().getTime(),
    diffSecs = 0,
    getNext = function () {
      if (timeIndex >= options.times.length) return false;
      preTarget = options.times[timeIndex];
      timeIndex++;

      return true;
    },
    getDiffSec = function () {

      diffSecs = Math.round((preTarget.parseDate('yyyy-MM-dd HH:mm:ss').getTime() - new Date().getTime() - diffMs) / 1000);
      diffSecs = diffSecs <= 0 ? 0 : diffSecs;
      return diffSecs;
    },
    render = function () {

      diffSecs--;
      if (diffSecs <= 0) {
        diffSecs = 0;
      }
      diff = {
        day: Math.floor(diffSecs / (24 * 60 * 60)),
        hour: (options.html.indexOf("{#day}") >= 0) ?
          Math.floor(diffSecs / 60 / 60) % 24 :
          Math.floor(diffSecs / 60 / 60),
        minute: Math.floor(diffSecs / 60) % 60,
        second: diffSecs % 60
      };

      var html = options.html.replace(/{#day}/g, diff.day > 9 ? diff.day : "0" + diff.day).replace(/{#hours}/g, diff.hour > 9 ? diff.hour : "0" + diff.hour).replace(
        /{#minutes}/g, diff.minute > 9 ? diff.minute : "0" + diff.minute).replace(/{#seconds}/g, diff.second > 9 ? diff.second : "0" + diff.second);
      obj.html(html);

      return (diffSecs <= 0) ? false : true;
    };

  if (!options.times) {
    options.times = [options.endTime];
  }

  clearInterval(timer);
  while (getNext()) {
    if (getDiffSec() <= 0)
      continue;
    break;
  }

  if (!render()) {
    return;
  }

  timer = setInterval(function () {

    if (!render()) {

      if (options.callback) {
        options.callback(options);
      }

      if (!getNext()) {
        clearInterval(timer);
      } else {
        getDiffSec();
      }
    }
  }, 1000);

  obj.data("countdown", timer);
};
var detailContentHeigh = 0;
var productParameterHeight = 0;
var packageServiceHeight = 0;
var customerServiceHeight = 0;
var tit1 = 0;
var tit2 = 0;
var tit3 = 0;
var tit4 = 0;
var oTop = 0;
var clickFlag = false;
var packFlag = false;
var commentFlag = false;
var scollFlag = false;
var upDownButton = "";
var finished = true;

//每个SKU对应的包装清单
ec.product.packageList = {};
//每个SKU对应的售后服务
ec.product.warranty = {};


$(function () {


  $(window).resize(function () {
    var sku = ec.product.getSku();
    var json = ec.product.getSkuInfo(sku);
    if (upDownButton == "true") {
      $('#pro-detail-content-' + json.id).height($('#kindPicture-' + json.id).height() + $('#pro-detail-up-btn-' + json.id).height() + 40);
    }
    if ($('#kindPicture-' + json.id).height() <= 2000) {
      $('#pro-detail-content-' + json.id).height($('#kindPicture-' + json.id).height());
      $('#detail-content-button-' + json.id).hide();
      $("#pro-detail-up-btn-" + json.id).css("display", "none");
    } else {
      if (upDownButton == "true") {
        $('#detail-content-button-' + json.id).hide();
        $("#pro-detail-up-btn-" + json.id).css("display", "block");
      } else if (upDownButton == "false") {
        $('#detail-content-button-' + json.id).show();
        $("#pro-detail-up-btn-" + json.id).css("display", "none");
      } else {
        $('#pro-detail-content-' + json.id).height('2000');
        $('#detail-content-button-' + json.id).show();
        $("#pro-detail-down-btn-" + json.id).click(function () {
          $('#pro-detail-content-' + json.id).height($('#kindPicture-' + json.id).height() + $('#pro-detail-up-btn-' + json.id).height() + 40);
          $('#detail-content-button-' + json.id).hide();
          $("#pro-detail-up-btn-" + json.id).css("display", "block");
          upDownButton == "true";
        });

        $("#pro-detail-up-btn-" + json.id).click(function () {
          $('#pro-detail-content-' + json.id).height('2000');
          $('#detail-content-button-' + json.id).show();
          $("#pro-detail-up-btn-" + json.id).css("display", "none");
          $("body,html").animate({
            scrollTop: tit1 + 1575
          }, 0);
          upDownButton == "false";
        });
      }
    }
  });


  $("#myConsultation").click(function () {
    _paq.push(['trackLink', 'Click PC_makeinquiry', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#myConsultation").hide();
    $("#upUserAdvisory").removeClass("hide").addClass("show");
    $("#stopConsultationId").show();
  });


  oTop = $(".product-tab").offset().top;
  $('#pro-tab-feature').click(function () {
    if (!clickFlag) {
      tit1 = $(".tit1").offset().top - 150;
      if (scollFlag) {
        tit1 = $(".tit1").offset().top - 50;
      }
      clickFlag = true;
    }
    $('#pro-tab-feature').addClass("selected").siblings().removeClass("selected");
    $("body,html").animate({
      scrollTop: tit1 + 75
    }, 0);
    //					//console.log("=========click1====="+tit1);
  });

  $('#pro-tab-parameter').click(function () {
    if (!clickFlag) {
      tit1 = $(".tit1").offset().top - 150;
      if (scollFlag) {
        tit1 = $(".tit1").offset().top - 50;
      }
      clickFlag = true;
    }
    $('#pro-tab-parameter').addClass("selected").siblings().removeClass("selected");
    tit2 = tit1 + $('#pro-tab-feature-content').height() + $('#hr60Detail').height();
    $("body,html").animate({
      scrollTop: tit2
    }, 0);
    //					//console.log("=========click2====="+tit2);
  });

  $('#pro-tab-package-service').click(function () {
    if (!clickFlag) {
      tit1 = $(".tit1").offset().top - 150;
      if (scollFlag) {
        tit1 = $(".tit1").offset().top - 50;
      }
      clickFlag = true;
    }
    $('#pro-tab-package-service').addClass("selected").siblings().removeClass("selected");
    tit3 = tit1 + $('#pro-tab-feature-content').height() + $('#hr60Detail').height() + $('#productParameter').height() + $('#hr60Detail').height();
    $("body,html").animate({
      scrollTop: tit3
    }, 0);
    //					//console.log("=========click3====="+tit1);
  });

  $('#pro-tab-evaluate').click(function () {
    if (!clickFlag) {
      tit1 = $(".tit1").offset().top - 150;
      if (scollFlag) {
        tit1 = $(".tit1").offset().top - 50;
      }
      clickFlag = true;
    }
    $('#pro-tab-evaluate').addClass("selected").siblings().removeClass("selected");
    tit4 = tit1 + $('#pro-tab-feature-content').height() + $('#hr60Detail').height() + $('#productParameter').height() + $('#hr60Detail').height() + $('#packagId').height() + $('#customerServiceLocation').height() + $('#productDetailstips').height();
    $("body,html").animate({
      scrollTop: tit4
    }, 0);
    //					//console.log("=========click4====="+tit1);
  });
  //				 //console.log("=========tit1====="+($(".tit1").offset().top -150));
  $(window).scroll(function () {
    var top = $(this).scrollTop() + 1;
    detailContentHeight = $('#pro-tab-feature-content').height() + $('#hr60Detail').height();
    productParameterHeight = $('#productParameter').height() + $('#hr60Detail').height();
    packageServiceHeight = $('#packagId').height();
    customerServiceHeight = $('#customerServiceLocation').height() + $('#productDetailstips').height();
    if (top > oTop) {
      $('.product-tab').addClass('product-tab-top')
        .css({
          "position": "fixed",
          "top": "0",
          "background": "#fff",
          "width": "100%",
          "z-index": "100"
        });
      $(".product-tab-btn").css({
        "display": "block"
      });
      if (!clickFlag) {
        tit1 = $(".tit1").offset().top - 50;
        //				//console.log("=========scrollfix====="+tit1)
      }
      scollFlag = true;
      //				//console.log("scollFlagfix="+scollFlag);
    } else {
      $('.product-tab').css({
        "position": "static"
      });
      $(".product-tab-btn").css({
        "display": "none"
      });

      $('.product-tab').removeClass('product-tab-top');
      if (!clickFlag) {
        tit1 = $(".tit1").offset().top - 150;
        //				//console.log("=========scrollUnfix====="+tit1)
      }
      scollFlag = false;
      //				//console.log("scollFlagUnfix="+scollFlag);
    }
    //			//console.log("top="+top);
    if (top >= (tit1 + 75) && top < (tit1 + detailContentHeight)) {
      //				//console.log((tit1+75)+"<top1<"+(tit1 + detailContentHeight));
      $('#pro-tab-feature').addClass('selected').siblings().removeClass('selected');
    }
    if (packFlag == true) {
      if (top >= (tit1 + detailContentHeight) && top < (tit1 + detailContentHeight + productParameterHeight + $('#productDetailstips').height())) {
        //					//console.log((tit1 + detailContentHeight)+"<top22<"+(tit1 + detailContentHeight + productParameterHeight+ $('#productDetailstips').height()));
        $('#pro-tab-parameter').addClass('selected').siblings().removeClass('selected');
      }
    } else {
      if (top >= (tit1 + detailContentHeight) && top < (tit1 + detailContentHeight + productParameterHeight)) {
        //					//console.log((tit1 + detailContentHeight)+"<top23<"+(tit1 + detailContentHeight + productParameterHeight));
        $('#pro-tab-parameter').addClass('selected').siblings().removeClass('selected');
      }
    }

    if (packFlag == false) {
      if (top >= (tit1 + detailContentHeight + productParameterHeight) && top < (tit1 + detailContentHeight + productParameterHeight + packageServiceHeight + customerServiceHeight)) {
        //				//console.log((tit1 + detailContentHeight + productParameterHeight)+"<top3<"+(tit1 + detailContentHeight + productParameterHeight + packageServiceHeight + customerServiceHeight));
        $('#pro-tab-package-service').addClass('selected').siblings().removeClass('selected');
      }
    }
    if (!commentFlag) {
      if (top >= (tit1 + detailContentHeight + productParameterHeight + packageServiceHeight + customerServiceHeight)) {
        //				//console.log("top>4"+(tit1 + detailContentHeight + productParameterHeight + packageServiceHeight + customerServiceHeight));
        $('#pro-tab-evaluate').addClass('selected').siblings().removeClass('selected');
      }
    }
  });

});

//数字工具
ec.ui.proNumer = function (selector, options) {
  //自定义购物车商品数量，只能输入数字
  var defaultOpt = {
      max: null,
      min: null,
      showButton: true,
      minusBtn: '<a id="pro-quantity-minus" href="javascript:;">&minus;</a>',
      plusBtn: '<a id="pro-quantity-plus" href="javascript:;">&#43;</a>'
    },
    thix = $(selector),
    options = $.extend(defaultOpt, options),
    checkNumber = function (e) { //限制输入，只能为数字
      var currentKey = e.which,
        val = parseInt(this.value, 10),
        thisVal = (val < 1) ? 1 : val;

      if ((currentKey < 37 || currentKey > 40) && currentKey != 8 && currentKey != 46) {

        if (thisVal > options.max || thisVal < options.min) {
          e.preventDefault();
          return false;
        } else {
          if ((currentKey < 48 || currentKey > 57) && (currentKey < 96 || currentKey > 105) && currentKey != 9) {
            e.preventDefault();
            return false;
          }

        }

      }
    };

  thix.each(function () {

    var opt = $.extend({}, options),
      inputObj = $(this).css('ime-mode', 'disabled');

    var tmp = inputObj.attr("max");
    if (tmp) {
      options.max = opt.max = parseInt(tmp, 10) || opt.max;
    }

    tmp = inputObj.attr("min");
    if (tmp) {
      options.min = opt.min = parseInt(tmp, 10) || opt.min;
    }

    if (opt.showButton) {
      //减少
      var minusBtn = $(opt.minusBtn).click(function () {
          var val = inputObj.val() || 0,
            thisVal = parseInt(val, 10) - 1;
          if (typeof (opt.min) == "number" && thisVal < opt.min) {
            return;
          }
          inputObj.val(thisVal).trigger("blur");
        }),
        //增加
        plusBtn = $(opt.plusBtn).click(function () {
          var val = inputObj.val() || 0,
            thisVal = parseInt(val, 10) + 1;
          if (typeof (opt.max) == "number" && thisVal > opt.max) {
            return;
          }
          inputObj.val(thisVal).trigger("blur");
        });
      //			inputObj.after(plusBtn.after(minusBtn).wrap('<p class="pro-stock-btn"></p>'));
      var temp = $('<p class="product-stock-btn"></p>').append(plusBtn).append(minusBtn)
      inputObj.after(temp);


      if (this.value <= 1) {
        $("#pro-quantity-minus").removeClass().addClass("disabled");
      } else {
        $("#pro-quantity-minus").removeClass();
      }

    }
    inputObj.data("ovalue", inputObj.val() || 0)
      .keydown(checkNumber)
      .keyup(function () {
        var thisVal = parseInt(this.value || 0);
        if (typeof (opt.min) == "number" && thisVal < opt.min) {
          this.value = opt.min;
          return;
        } else if (typeof (opt.max) == "number" && thisVal > opt.max) {
          this.value = opt.max;
          return;
        }
      })
      .blur(function () {

        if (this.value <= 1) {
          $("#pro-quantity-minus").removeClass().addClass("disabled");
        } else {
          $("#pro-quantity-minus").removeClass();
        }

        if (typeof opt.onchange === "function") {
          var oldVal = inputObj.data("ovalue"),
            newVal = this.value || 0,
            diff = parseInt(newVal, 10) - parseInt(oldVal, 10);
          if (diff == 0) return;
          inputObj.data("ovalue", newVal);
          opt.onchange.call(this, newVal, diff);

        }
      });

  });

};

ec.product.prefix = "/product";
ec.remark = {};
ec.remark.prefix = domainRemark + "/remark";

// 绑定邮箱
ec.product.email = ec.util.escapeHtml(ec.account.email);

// 绑定手机号码
ec.product.mobile = ec.util.escapeHtml(ec.account.mobile);

// 存放已经查过商品详情的sku id
var _skuForGetFeature = {};

(function () {
  var _preSku = null,
    isFirstIn = true,
    //存放查询规格参数已经查询过的sku id
    _skuForGetParement = {},
    //
    //		_skuForGetFeature={},
    _skuMap = {},
    //SKU属性显示方式  1图片,2文本
    _skuShowType = {},
    //SKU ID与属性名的映射关系
    //_skuAttrNameMap = {},
    //SKU属性ID与SKU的映射关系
    _skuAttrId2SkuMap = {},
    //SKU属性名ID
    _skuAttrTypeID = [],
    //SKU属性名
    _skuAttrName = [],
    //SKU属性值
    _skuAttrVallue = {},
    //SKU属性值对应的id
    _skuAttrType2ValueIds = {},
    //选中的SKU属性
    _selectAttrMap = {},
    _attrValue2SkuId = {}, //属性值对应商品SKUID
    _timer,
    //sku是否是优购码商品
    _skuPriority = {},
    _skuPointWeigth = {},
    _skuPointWeigthDetail = {};
  ec.product.getSkuPointWeight = function (skuCode) {
    return _skuPointWeigth[skuCode];
  };
  ec.product.setSkuPointWeight = function (skuCode, promotion) {
    _skuPointWeigth[skuCode] = promotion;
  };
  ec.product.getSkuPointWeightDetail = function (skuCode) {
    return _skuPointWeigthDetail[skuCode];

  }
  ec.product.setSkuPointWeightDetail = function (skuCode, promotion) {
    _skuPointWeigthDetail[skuCode] = promotion;

  }
  _proGallerysMouseOver = function () {
      var thix = $(this);

      thix.parent().parent().addClass("current").siblings().removeClass("current");

      clearTimeout(_timer);
      _timer = setTimeout(function () {
        var img = thix.attr("src");

        $("#product-img").attr("href", img.replace("55_55", "800_800")).find("img").attr("src", img.replace("55_55", "428_428"));

        //重新设置放大镜
        $("#product-img").CloudZoom();
      }, 150);
    },
    _updateSelect = function () {

      var selectPara = "";
      $("#pro-skus").find('.selected').each(function () {
        selectPara += $(this).children().children("a").attr("title") + " / ";
      });
      //获取用户选中的延保商品名称
      var temp1 = "",
        temp2 = "";
      $("#extendProtected ul li").each(function (index) {
        if ($(this).hasClass('selected')) {
          temp1 = $(this).find("a").attr("title");
          return;
        }
      });
      $("#accidentProtected ul li").each(function (index) {
        if ($(this).hasClass('selected')) {
          temp2 = $(this).find("a").attr("title");
          return;
        }
      });

      if (temp1 != "无需延保" && temp1 != "") {
        selectPara += temp1 + " / ";
      }
      if (temp2 != "无需碎屏保" && temp2 != "") {
        selectPara += temp2 + " / ";
      }

      selectPara = selectPara.substring(0, selectPara.length - 2);

      selectPara += "";
      $("#pro-select-sku").html(selectPara);
      $("#pro-select-sku").parent().show();
    };
  _upadteSkuPrice = function (sku) {
    //价格
    if (sku.priceMode != 2) {
      sku.price = parseFloat(sku.price).toFixed(2);
    }

    //如果两个价格相等 则显示华为价和现价 否则只有 华为价
    if (parseFloat(sku.originPrice) != parseFloat(sku.price) && (sku.priceMode != 2)) {
      $("#pro-price-label").html('抢购价');
      $("#pro-price").html('&yen;&nbsp;' + sku.price);
      $("#pro-price-old").html('&yen;&nbsp;' + sku.originPrice);
      $("#pro-price-label").show();
      $("#pro-price").show();
      $("#pro-price-old").show();
      //临时注释掉
      //				if(sku.price > 0)
      //					$("#pro-price").html('<label>现&nbsp;价：</label><b>&yen;&nbsp;'+  sku.price + '</b>');
    } else {
      $("#pro-price-old").hide();
      $("#pro-price-label").hide();
      $("#pro-price-old").html('');
      $("#pro-price-label").html('')
      if (sku.price > 0) {
        $("#pro-price").html('&yen;&nbsp;' + sku.price);
        $("#pro-price").show();
      } else {
        $("#pro-price").html('');
        $("#pro-price").hide();
        $("#pro-price-label").html('暂无报价');
        $("#pro-price-label").show();

      }
    }
    //价格显示方式，1：正常显示；2：暂不报价
    if (sku.priceMode == 2 || sku.price <= 0) {
      $("#pro-price").hide();
      $("#pro-price-old").hide();
      $("#pro-price-label").html('暂无报价');
      $("#pro-price-label").show();

    }
  };

  //更新当前SKU的页面的信息
  _updateSkuInfo = function () {

    var sku = ec.product.getSku(),
      //skuPromWord;
      timerPromWord;

    if (!sku || _preSku == sku) {
      return;
    } else {
      //切换sku视频隐藏
      ec.product.videoHide();
    }
    ec.product.setSkuId = _preSku = sku;


    $("#product-tips").hide();
    //$("#product-operation").show();


    //重新初始化商品数量与按钮操作区
    $("#pro-quantity-area").show();
    $("#pro-operation").css("visibility", "visible");
    $("#pro-quantity-area").show();
    $("#pro-quantity-area-nochange").hide();

    $("#product-operation").hide(); //console.log("product-operation.hide()");



    var bundleList = $("#bundle-list-" + sku);

    if (bundleList && bundleList.length > 0) {
      $("#product-package-area").show();
    } else {
      $("#product-package-area").hide();
    }


    sku = _skuMap[sku];

    ec.product.setType(sku.type);

    //抽取更新价格方法
    _upadteSkuPrice(sku);

    //广告语
    var html = [];
    html.push('<a href="javascript:;" class="product-slogan-btn"></a>');

    if ($.trim(sku.timerPromWord).length > 0) {
      if ($.trim(sku.timerPromLink4PC).length > 0) {
        timerPromWord = '<a href="' + sku.timerPromLink4PC +
          '" target="_blank"   onclick='
        _paq.push(["trackLink", "Click pc_promotion_ads", "link", ""]);
        ec.code.addAnalytics({
          hicloud: true
        })
        ' class="product-slogan-link">' + sku.timerPromWord + '</a>';
      }
      var _now = ec.product.getSysDate();
      var start = sku.timerPromStarttime;
      var startTime = new Date();
      startTime.setTime(start.parseDate('yyyy-MM-dd HH:mm:ss'));
      var end = sku.timerPromEndtime;
      var endTime = new Date();
      endTime.setTime(end.parseDate('yyyy-MM-dd HH:mm:ss'));

      if ((_now - startTime) >= 0 && (endTime - _now) >= 0) {
        html.push(timerPromWord || '<span class="product-slogan-link">' + sku.timerPromWord + "</span>");
      }
    }
    if ($.trim(sku.skuPromWord).length > 0) {
      html.push('<span>' + sku.skuPromWord + '</span>');
    }
    if (0 < html.length) {
      $("#skuPromWord").html(html.join(" "));
      $('#skuPromWord').show();
      $('.product-slogan-btn').hide();
      $("#skuPromWord").attr("class", "product-slogan");
      var nowHeight = $("#skuPromWord").height();
      if (nowHeight > 36) {
        $("#skuPromWord").attr("class", "product-slogan product-slogan-hide");
        $('.product-slogan-btn').show();
        $('.product-slogan-btn').click(function () {
          if ($("#skuPromWord").hasClass("product-slogan-show")) {
            $("#skuPromWord").attr("class", "product-slogan product-slogan-hide");
          } else {
            $("#skuPromWord").attr("class", "product-slogan product-slogan-show");
          }
          //						_paq.push(['trackLink','Click pc_promotion_ads', 'link', ' ']);
          //						ec.code.addAnalytics({hicloud:true});
        });
      }
    } else {
      $('#skuPromWord').html('');
      $('#skuPromWord').hide();
    }



    //商品编码
    $("#pro-sku-code").val(sku.code);
    $("#pro-sku-code2").text(sku.code);

    //渲染标题
    $("#pro-name").html(sku.name);
    $("#bread-pro-name").html(sku.name);

    //渲染库存区域
    ec.product.execute("renderInventory", [ec.product.inventory.haveInventory(sku.id)]);

    //套图 start
    $("#product-img").attr("href", ec.mediaPath + sku.photoPath + "800_800_" + sku.photoName).find("img")
      .attr("src", ec.mediaPath + sku.photoPath + "428_428_" + sku.photoName);
    //重新设置放大镜
    $("#product-img").CloudZoom();

    var html = [];
    html.push('<li class="current"><a href="javascript:;"><img src="' + ec.mediaPath + sku.photoPath + '55_55_' + sku.photoName + '" alt="' + sku.name + '"/></a></li>');
    if (sku.groupPhotoList) {
      for (var i = 0; i < sku.groupPhotoList.length; i++) {
        var c = sku.groupPhotoList[i];
        html.push('<li><a href="javascript:;"><img src="' + ec.mediaPath + c.path + '/55_55_' + c.name + '"  alt="' + sku.name + '"/></a></li>');
      }

    }
    //套图 end

    html = $(html.join(""));
    html.find("img").mouseover(_proGallerysMouseOver);
    $("#pro-gallerys").empty().html(html);
    ec.product.imgSlider.reset();


    //促销消息
    html = [], htmldetail = [];
    var isShowPromotions = false,
      isShowGifts = false;
    if (!sku.promotionLst || sku.promotionLst.length == 0) {
      $("#pro-promotions-list").html("");
      $("#pro-promotions-list").hide();
      $("#pro-promotions-list-detail").hide();
      $("#pro-promotions-list-detail").html('');
    } else {
      for (var i = 0; i < sku.promotionLst.length; i++) {
        html.push('<li><strong></strong><span>' + sku.promotionLst[i].promoLabel + '</span>');
        html.push('</li>');
        htmldetail.push('<li><strong></strong><span>' + sku.promotionLst[i].promoLabel + '</span><p>' + sku.promotionLst[i].ruleDescription);
        //需要实名认证
        if (sku.promotionLst[i].isRealNameAuth == "1") {
          htmldetail.push('<a href="/authmember/accesstoken" target="_blank">&nbsp;限实名用户参加 ></a>');
        }
        htmldetail.push('</p>');
        htmldetail.push('</li>')
      }
      $("#pro-promotions-list").html(html.join(""));
      $("#pro-promotions-list-detail").html(htmldetail.join(""));
      isShowPromotions = true;

      //#pro-promotions-list下面的li标签只显示三个 超过的隐藏
      $('#pro-promotions-list li').hide();
      for (var i = 0; i < 3; i++) {
        $('#pro-promotions-list li').eq(i).show();
      }


      $("#pro-promotions-list").show();
      $("#pro-promotions-list-detail").show();
    }
    //赠品
    html = [];
    if (!sku.giftList || sku.giftList.length == 0) {
      isShowGifts = false;
    } else {
      isShowGifts = true;
    }
    if (isShowGifts) {
      $("#pro-gift").show();
      $("#pro-gift-list-select").html(ec.product.gift.ftl(ec.product.getSku()));
    } else {
      $("#pro-gift").hide();
    }

    //服务说明----start
    html = [];
    if (ec.product.seCode != ec.product.productSeCode) {
      html.push('<p>已包邮<em></em>由' + ec.product.productshopName + '发货，并提供售后服务</p>');
    } else {
      if (parseFloat(ec.product.deliveryModeValueFreeBase) > 0 && ec.product.productType == 0) {
        if (sku.priceMode != 2) {
          if (parseFloat(sku.price) >= parseFloat(ec.product.deliveryModeValueFreeBase)) {
            html.push('<p>已满' + ec.product.deliveryModeValueFreeBase + '元已免运费<em></em>');
          } else {
            html.push('<p>满' + ec.product.deliveryModeValueFreeBase + '元即免运费，快去凑单吧<em></em>');
          }
        }
      } else {
        html.push('<p>');
      }
      html.push('由华为商城负责发货，并提111供售后服务</p>');

    }
    //$("#service-description").html(html.join(" "));
    //服务说明----end

    //如果本主商品绑定了 服务商品（延保，意外保）
    if (sku.prolongLst.length > 0) {
      var lst;
      html = [];
      //定义延保服务的商品id
      var ExtendedProtectProductId = [];
      //定义意外保的商品Id数组
      var accidentProtectProductId = [];
      //定义延保服务的名字数组
      var ExtendedProtectName = [],
        ExtendedProtectBrifeName = [];
      //定义延保服务的Id数组
      var ExtendedProtectId = [];
      //定义延保服务的个数
      var ExtendedProtectNum = 0;
      var ExtendedOption;
      //定义意外保的名字数组
      var accidentProtectName = [],
        accidentProtectBrifeName = [];

      //定义意外保的Id数组
      var accidentProtectId = [];
      //定义意外保的个数
      var accidentProtectsNum = 0;
      //定义页面中延保商品选项长度
      var entendOptionSize = 0;
      //定义页面中意外保商品选项长度
      var accidentOptionSize = 0;
      var ifShowServicePlusFlag = 0;


      var extendedProtectCode = [];
      var accidentProtectCode = [];


      for (var i = 0; i < sku.prolongLst.length; i += 1) {
        lst = sku.prolongLst[i];
        //如果该商品绑定了延保服务
        if (lst.serviceType == 1) {
          ExtendedProtectName[ExtendedProtectNum] = lst.name;
          ExtendedProtectId[ExtendedProtectNum] = lst.id;
          extendedProtectCode[ExtendedProtectNum] = lst.sbomCode;
          ExtendedProtectProductId[ExtendedProtectNum] = lst.productId;
          ExtendedProtectBrifeName[ExtendedProtectNum] = lst.brifeName;
          ExtendedProtectNum += 1;
        }
        //如果该商品绑定了意外保服务
        if (lst.serviceType == 2) {
          accidentProtectName[accidentProtectsNum] = lst.name;
          accidentProtectId[accidentProtectsNum] = lst.id;
          accidentProtectCode[accidentProtectsNum] = lst.sbomCode;
          accidentProtectProductId[accidentProtectsNum] = lst.productId;
          accidentProtectBrifeName[accidentProtectsNum] = lst.brifeName;
          accidentProtectsNum += 1;
        }
      }

      //清空延保商品
      $("#extendProtected").find("ul").html("");
      //清空意外保商品
      $("#accidentProtected").find("ul").html("");
      $('#pro-service').hide();
      $("#extendSelect").attr("skuid", "");
      $("#extendSelect").attr("data-scode", "");
      $("#accidentSelect").attr("skuid", "");
      $("#accidentSelect").attr("data-scode", "");
      $("#extendSelect").html("");
      $("#accidentSelect").html("");
      $("#servicePlus").hide();
      $("#service-choose").show();
      $(".product-operation-main").css("min-height", "49px");

      if (ExtendedProtectNum > 0 || accidentProtectsNum > 0) {
        $("#pro-service").show();
      } else {
        $("#pro-service").hide();
      }
      //如果延保服务个数大于0
      if (ExtendedProtectNum > 0) {
        //显示延保商品模块
        $("#extendProtected").parent().show();

        ExtendedOption = $('<li class="selected"><a id="-1" title="无需延保">无需延保</a></li>');
        ExtendedOption.appendTo($("#extendProtected").find("ul"));
        for (var i = 0; i < ExtendedProtectNum; i++) {
          //定义延保选项内容
          ExtendedOption = $('<li><a id="' + ExtendedProtectProductId[i] + '"href="javascript:;" title="' + ExtendedProtectBrifeName[i] + '" skuID="' + ExtendedProtectId[i] + '" data-scode="' + extendedProtectCode[i] + '" >' + ExtendedProtectName[i] + '</a></li>');
          //将延保选项内容加到下拉列表中
          ExtendedOption.appendTo($("#extendProtected").find("ul"));
        }
        ec.product.serverCommodity('extendProtected');
        $('#extendProtected>p>a').hide();
      } else {
        //隐藏延保服务商品模块
        $("#extendProtected").parent().hide();
      }
      //如果意外保服务个数大于0
      if (accidentProtectsNum > 0) {
        //显示意外保商品模块
        $("#accidentProtected").parent().show();
        //将意外保服务的文本框内容设置为第一个意外保商品名称
        var accidentOption = "";
        accidentOption = $('<li class="selected"><a id="-1" title="无需碎屏保" >无需碎屏保</a></li>');
        accidentOption.appendTo($("#accidentProtected").find("ul"));
        for (var i = 0; i < accidentProtectsNum; i++) {
          //定义意外保选项内容
          accidentOption = $('<li><a id="' + accidentProtectProductId[i] + '"href="javascript:;" title="' + accidentProtectBrifeName[i] + '"  skuID="' + accidentProtectId[i] + '" data-scode="' + accidentProtectCode[i] + '">' + accidentProtectName[i] + '</a></li>');
          //将意外保选项内容加到下拉列表中
          accidentOption.appendTo($("#accidentProtected").find("ul"));
        }
        ec.product.serverCommodity('accidentProtected');
        $('#accidentProtected>p>a').hide();
      } else {
        //隐藏意外保服务商品模块
        $("#accidentProtected").parent().hide();
      }

      //单击延保类型  意外保类型事件
      $("#extendProtected a,#accidentProtected a").click(function () {
        //用户选择去除掉当前服务商品
        if ($(this).parent().hasClass("selected")) {
          //删除文本框的高选样式
          $(this).parent().removeClass("selected");
          //删除当前文本框下拉列表中的高选样式
          $(this).next("ul").find("li").removeClass("selected");
        }
        //如果用户单击延保服务商品
        if ($(this).parent().parent().parent().is("#extendProtected")) {
          //将当前延保服务选项加上高选样式
          var productId = $(this).attr('id'),
            name = $(this).attr("title");
          if (productId != -1) {
            $('#extendProtected>p>a').show();
            $('#extendProtected>p>a').attr('id', productId);
            $('#extendProtected>p>a').attr('href', '/product/' + productId + '.html');

          } else {
            $('#extendProtected>p>a').hide();
            name = "";
          }
          if ($("#accidentSelect").html().length == 0) {
            if (name.length == 0) {
              $("#service-choose").show();
              $("#extendSelect").html("");
              $("#extendSelect").attr("skuid", "");
              $("#extendSelect").attr("data-scode", "");
              $("#servicePlus").hide();
            } else {
              $("#service-choose").hide();
              $("#extendSelect").html(name);
              $("#extendSelect").attr("skuid", $(this).attr("skuID"));
              $("#extendSelect").attr("data-scode", $(this).attr("data-scode"));
            }
          } else {
            if (name.length == 0) {
              $("#service-choose").hide();
              $("#servicePlus").hide();
              $("#extendSelect").html("");
              $("#extendSelect").attr("skuid", "");
              $("#extendSelect").attr("data-scode", "");
            } else {
              $("#extendSelect").html(name);
              $("#service-choose").hide();
              $("#servicePlus").show();
              $("#extendSelect").attr("skuid", $(this).attr("skuID"));
              $("#extendSelect").attr("data-scode", $(this).attr("data-scode"));
            }
          }
          var currentExtendLi = $(this).parent();
          currentExtendLi.addClass("selected");
          //将其他延保服务选项去掉高选样式
          $(this).parent().siblings("li").not(currentExtendLi).removeClass("selected");


        }
        //如果用户单击意外保服务商品
        if ($(this).parent().parent().parent().is("#accidentProtected")) {
          //将当前意外保服务选项加上高选样式
          var productId = $(this).attr('id'),
            name = $(this).attr("title");
          if (productId != -1) {
            $('#accidentProtected>p>a').show();
            $('#accidentProtected>p>a').attr('id', productId);
            $('#accidentProtected>p>a').attr('href', '/product/' + productId + '.html');
          } else {
            $('#accidentProtected>p>a').hide();
            name = "";
          }
          if ($("#extendSelect").html().length == 0) {
            if (name.length == 0) {
              $("#service-choose").show();
              $("#accidentSelect").html("");
              $("#accidentSelect").attr("skuid", "");
              $("#accidentSelect").attr("data-scode", "");
              $("#servicePlus").hide();
            } else {
              $("#service-choose").hide();
              $("#accidentSelect").html(name);
              $("#accidentSelect").attr("skuid", $(this).attr("skuID"));
              $("#accidentSelect").attr("data-scode", $(this).attr("data-scode"));
            }
          } else {
            if (name.length == 0) {
              $("#service-choose").hide();
              $("#servicePlus").hide();
              $("#accidentSelect").html("");
              $("#accidentSelect").attr("skuid", "");
              $("#accidentSelect").attr("data-scode", "");
            } else {
              $("#accidentSelect").html(name);
              $("#accidentSelect").attr("skuid", $(this).attr("skuID"));
              $("#accidentSelect").attr("data-scode", $(this).attr("data-scode"));
              $("#service-choose").hide();
              $("#servicePlus").show();
            }
          }
          var currentAccidentLi = $(this).parent();
          currentAccidentLi.addClass("selected");
          //将其他意外保服务选项去掉高选样式
          $(this).parent().siblings("li").not(currentAccidentLi).removeClass("selected");
        }
        _updateSelect();
        _paq.push(['trackLink', 'Click PC_additional-service', 'link', ' ']);
        ec.code.addAnalytics({
          hicloud: true
        });
      });
      $('#pro-service').show();
    } else {
      //隐藏购物服务模块
      $('#pro-service').hide();
      $("#extendSelect").attr("skuid", "");
      $("#extendSelect").attr("data-scode", "");
      $("#accidentSelect").attr("skuid", "");
      $("#accidentSelect").attr("data-scode", "");
      $("#extendSelect").html("");
      $("#accidentSelect").html("");
      $("#servicePlus").hide();
      $("#service-choose").show();
      //				$(".product-operation-main").css("min-height","99px");
      $("#extendProtected ul").each(function (index) {
        $(this).html("");
      });
      $("#accidentProtected ul").each(function (index) {
        $(this).html("");
      });
    }

    _updateSelect();
    // 合约机
    ec.product.initContract(sku);

    //赠送积分
    $("#integral").html(sku.integral);

    //捆绑和组合套装
    ec.product.renderGroup(_preSku);
    //2016-08-29 修改切換sku時 頁面始終停留在商品詳情tab頁
    //			$("#pro-tab-feature").siblings().removeClass("current");
    //			$("#pro-tab-feature").addClass("current");
    //$("#pro-tab-feature-content").show().siblings().hide();


    //切换商品介绍信息
    //ec.product.tabSkuInfo(_preSku);




    //切换sku时，更新订金信息
    if (ec.product.productType == 4) {
      //查询订金活动信息
      ec.product.depositActivity(ec.product.getSku());
    } else {
      //抢购活动业务逻辑处理入口
      if ($("#pro-global-parameter").attr("data-skulist-rushbuy")) {
        ec.product.rushbuyActivity();
      }
    }
    //console.log($("#pro-global-parameter").attr("data-skulist-rushbuy"));


    var sku = ec.product.getSku();
    packFlag = false;
    sku = ec.product.getSkuInfo(sku);
    upDownButton = "";
    ec.product.getFeature(sku.id);
    ec.product.getParameter(sku.id, sku.code);

    ec.product.getPackageAndService(sku.id);
    ec.product.switchSku();
    $(".product-tab-btn").css({
      "display": "none"
    });
    //根据选中的SKU调用预计送达时间的业务逻辑处理方法
    ec.product.processSupportDisplayDilieryTime(sku);

    //是否显示购买送积分
    ec.product.queryPointWeight(ec.product.setSkuId || ec.product.defaultSku);

    //加载优惠券信息
    ec.product.coupon.loadCoupon(sku.code);

  };
  //切换显示当前选中的sku商品的相关信息
  ec.product.tabSkuInfo = function (skuId) {
    $('#pro-tab-feature-content-' + skuId +
      ', #pro-tab-feature-content2-' + skuId +
      ', #pro-tab-parameter-content-' + skuId +
      ', #pro-tab-package-content-' + skuId +
      ', #pro-tab-service-content-' + skuId).show().siblings().hide();

    $("#comb-pro-area").find(".selected").each(function () {
      $(this).removeClass("selected");
    });

    $("#comb-count").html("0");

    var count = parseInt($("#comb-count").html(), 10) && 0;
    var sku = ec.product.getSkuInfo(skuId);
    var price = parseFloat(sku.price);

    //当商品类型不是订金商品的时候才更新组合价，更新组合价交给ec.product.depositActivity
    if (!(ec.product.productType && ec.product.productType == 4 && ec.product.isDespositSku == 1)) {
      $("#comb-price-label").html("组合价：&yen;");
      $("#comb-price").html(price.toFixed(2));
    }

    $("#combList-list-" + skuId).show().siblings().hide();
    if (!($("#combList-list-" + skuId).children().eq(0).hasClass("current"))) {
      $("#combList-list-" + skuId).children().eq(0).addClass("current").siblings().removeClass("current");
    }

  };
  ec.product.addSkuAttr = function (skuId, attrTypeId, attrName, attrId, attrValue) {

    /**
     * SKU ID与属性值ID的关系
     * ex : 10 = [41 , 44]
     */
    var sku = _skuMap[skuId];
    if (!sku) {
      _skuMap[skuId] = {
        attrIds: [attrId]
      };
    } else {
      sku.attrIds.push(attrId);
    }


    /**
     * 属性值ID与SKU ID的关系
     * ex : 41 = 10
     */
    _skuAttrId2SkuMap[attrId] = skuId;


    /**
     * SKU属性与属性值的关系
     * ex : 尺寸 = [S , XL]
     */
    var attrV = _skuAttrVallue[attrName];
    if (!attrV) {
      _skuAttrName.push(attrName);
      _skuAttrTypeID.push(attrTypeId);
      _skuAttrVallue[attrName] = [attrValue];
    } else if (attrV.indexOf(attrValue) == -1) {
      attrV.push(attrValue);
    }

    /**
     * SKU属性名ID的不同的ID
     * ex : attrTypeId = [41 , 42]
     */
    var ids = _skuAttrType2ValueIds[attrTypeId + "-" + attrValue];
    if (!ids) {
      _skuAttrType2ValueIds[attrTypeId + "-" + attrValue] = [attrId];
    } else {
      ids.push(attrId);
    }
    //属性值对应 SKUID数组
    if (!_attrValue2SkuId[attrValue]) {
      _attrValue2SkuId[attrValue] = [];
    }
    _attrValue2SkuId[attrValue].push(skuId);


  };

  /**
   * 设置SKU其他属性
   */
  ec.product.setSku = function (skuId, options) {
    options = options || {};
    options.id = skuId;
    $.extend((_skuMap[skuId] || (_skuMap[skuId] = {})), options);
  };

  //获取选中的SKU
  ec.product.getSku = function () {
    var sku;
    //log(_selectAttrMap);
    $.each(_selectAttrMap, function () {
      if (!sku) {
        sku = this;
        return;
      }

      var _t = this,
        newSku = [];
      //
      for (var i = 0; i < sku.length; i++) {
        for (var j = 0; j < _t.length; j++) {
          if (sku[i] == _t[j]) {
            newSku.push(sku[i]);
          }
        }
      }
      sku = newSku;
    });
    //log("SKU",sku);
    if (!sku || sku.length != 1) {
      return (_preSku || ec.product.defaultSku);
    }

    return sku[0];
  };

  ec.product.getSkuInfo = function (skuId) {
    return _skuMap[skuId];
  };

  ec.product.setSkuForParement = function (skuId) {
    _skuForGetParement[skuId] = skuId;
  };
  ec.product.getSkuForParement = function (skuId) {
    return _skuForGetParement[skuId];
  };
  ec.product.setSkuForFeature = function (skuId) {
    _skuForGetFeature[skuId] = skuId;
  };
  ec.product.getSkuForFeature = function (skuId) {
    return _skuForGetFeature[skuId];
  };

  //设置SKU显示方式
  ec.product.setSkuShowType = function (attrTypeId, showType) {
    _skuShowType[attrTypeId] = showType;
  };
  ec.product.setSkuPriority = function (skuId) {
    _skuPriority[skuId] = true;
  };
  ec.product.getSkuPriority = function (skuId) {
    return _skuPriority[skuId];
  };




  //根据SkuId选中属性
  ec.product.selectBySku = function (skuId) {
    var sku = _skuMap[skuId];
    if (!sku || !sku.attrIds) {
      _upadteSkuPrice(sku);

      //重新初始化商品数量与按钮操作区
      //			$("#pro-quantity-area").show();
      //			$("#pro-operation").css("visibility" , "visible");
      //		    $("#pro-quantity-area").show();
      //			$("#pro-quantity-area-nochange").hide();
      //
      //			$("#product-operation").hide();//console.log("product-operation.hide()1");

      //如果sku没有配置商品属性且为订金商品，加载订金活动信息（因为没有配置商品属性时，没有调用_updateSkuInfo，导致订金活动信息没有加载）
      if (ec.product.productType == 4) {
        //查询订金活动信息
        ec.product.depositActivity(skuId);
      } else {
        //抢购活动业务逻辑处理入口（因为没有配置商品属性时，没有调用_updateSkuInfo，导致订金活动信息没有加载）
        if ($("#pro-global-parameter").attr("data-skulist-rushbuy")) {
          ec.product.rushbuyActivity();
        }
      }
      //没有配置Sku属性时，也需要调用预计送达时效提示相关方法
      //			ec.product.processSupportDisplayDilieryTime(sku) ;
      return;
    }
    $("#pro-skus").find(".attr" + sku.attrIds.join(",.attr")).children(".sku").trigger("click");
  };

  ec.product.queryPointWeight = function (skuId) {
    var sku = _skuMap[skuId];
    if (sku || sku.code) {
      //虚拟商品、代销商品不展示赠送积分
      //商品类别 0-实物商品 1-延保 2-Dbank套餐 3-代销商品 4-定金商品 5-music商品 6-意外保
      if (ec.product.productType == 1 || ec.product.productType == 2 ||
        ec.product.productType == 5 ||
        ec.product.productType == 6) {
        return;
      }

      //商品shopCode不为VMALL-HUAWEIDEVICE，则不是华为自营商品
      if (ec.product.seCode != "VMALL-HUAWEIDEVICE") {
        return;
      }

      //合约机不展示赠送积分
      if (sku.contractList && sku.contractList.length > 0) {
        return;
      }

      if (ec.product.getSkuPointWeight(sku.code) != undefined) {
        $("#pro-promotions-list").append(ec.product.getSkuPointWeight(sku.code));
        $("#pro-promotions-list-detail").append(ec.product.getSkuPointWeightDetail(sku.code));
        //#pro-promotions-list下面的li标签只显示三个 超过的隐藏
        $('#pro-promotions-list li').hide();
        for (var i = 0; i < 3; i++) {
          $('#pro-promotions-list li').eq(i).show();
        }
        $("#pro-promotions-list").show();
        $("#pro-promotions-list-detail").show();
        if ($("#pro-promotions-list").parent().parent().hasClass("hide")) {
          $("#pro-promotions-list").parent().parent().removeClass("hide")
        }
      } else {
        $.ajax({
          url: $("#domainUc").val() + "/point/queryPointWeight.json?sbomCode=" + sku.code,
          dataType: "jsonp",
          timeout: 10000,
          jsonpCallback: "queryPointWeightHandler",
          success: function (json) {

            var pointWeight = 1;
            if (json.resultCode == "200") {
              if (json.pointWeightMap != null) {
                for (var k in json.pointWeightMap) {

                  if (json.pointWeightMap[k] != null) {
                    pointWeight = json.pointWeightMap[k];
                  }
                }
              }
            }
            //0：积分翻倍 活动赠送翻倍积分，积分可抵现~；1：赠送积分  购买即赠商城积分，积分可抵现~
            //						html.push('<li><strong></strong><span>'+sku.promotionLst[i].promoLabel+'</span>');
            //						html.push('</li>');
            //						htmldetail.push('<li><strong></strong><span>'+sku.promotionLst[i].promoLabel+'</span><p>'+sku.promotionLst[i].ruleDescription+'</p>');
            //						//需要实名认证
            //						if(sku.promotionLst[i].isRealNameAuth == "1"){
            //							htmldetail.push('&nbsp;<a href="/authmember/accesstoken" target="_blank">&nbsp;限实名用户参加 ></a>');
            //						}
            //						htmldetail.push('</li>')
            var html = [],
              htmldetail = [];
            //						if(pointWeight == 0){
            //							html.push('<li><strong></strong><span>积分翻倍</span></li>');
            //							htmldetail.push('<li><strong></strong><span>积分翻倍</span><p>活动赠送翻倍积分，积分可抵现~</p>');
            //						}else
            if (pointWeight == 1) {
              html.push('<li><strong></strong><span>赠送积分</span></li>');
              htmldetail.push('<li><strong></strong><span>赠送积分</span><p>购买即赠商城积分，积分可抵现~</p>');
            } else {
              html.push('<li><strong></strong><span>积分翻倍</span></li>');
              htmldetail.push('<li><strong></strong><span>积分翻倍</span><p>活动赠送翻倍积分，积分可抵现~</p>');
            }
            $("#pro-promotions-list").append(html.join(" "));
            $("#pro-promotions-list-detail").append(htmldetail.join(" "));
            //#pro-promotions-list下面的li标签只显示三个 超过的隐藏
            $('#pro-promotions-list li').hide();
            for (var i = 0; i < 3; i++) {
              $('#pro-promotions-list li').eq(i).show();
            }
            $("#pro-promotions-list").show();
            $("#pro-promotions-list-detail").show();

            if ($("#pro-promotions-list").parent().parent().hasClass("hide")) {
              $("#pro-promotions-list").parent().parent().removeClass("hide");
            }
            ec.product.setSkuPointWeight(sku.code, html.join(" "));
            ec.product.setSkuPointWeightDetail(sku.code, htmldetail.join(" "));
          }
        });
      }


    }
  };

  ec.ready(function () {
    //首先隐藏预计送达时效提示
    ec.product.hiddenTips();
    //初始化隐藏图文详情tab块的按钮
    $(".product-tab-btn").css({
      "display": "none"
    });

    //构造显示SKU属性
    var html = [],
      attrTypeId, attrName, attrValueIds, showText;

    for (var i = 0; i < _skuAttrName.length; i++) {
      attrTypeId = _skuAttrTypeID[i];
      showText = (_skuShowType[attrTypeId] == "2");
      //属性类型, ex:颜色
      attrName = _skuAttrName[i];
      if (showText) {
        html.push('<dl class="product-choose clearfix"><label>选择' + attrName + '</label><div class="product-choose-detail"><ul>');
      } else {
        html.push('<dl class="product-choose product-choosepic clearfix"><label>选择' + attrName + '</label><div class="product-choose-detail"><ul>');
      }

      //属性值文字, ex:红色, 绿色
      var values = _skuAttrVallue[attrName];
      for (var j = 0; j < values.length; j++) {
        //属性值的ids , ex: [16 , 17]
        attrValueIds = _skuAttrType2ValueIds[attrTypeId + "-" + values[j]];
        html.push('<li class=" attr' + attrValueIds.join(" attr") + '" data-attrName="' + attrName + '" data-attrId="' + attrValueIds.join(",") + '" data-skuId="' + _attrValue2SkuId[values[j]].join(",") + '"><div class="sku"><a  href="javascript:;" title="' + values[j] + '">');
        if (showText) {
          html.push('<p><span>');
          html.push(values[j]);
          html.push('</span></p></a>');
        } else {
          //ex: sku = skuMap[ arrrId2skuId[attrId] ]
          var sku = _skuMap[_skuAttrId2SkuMap[attrValueIds[0]]];
          html.push('<img src="' + ec.mediaPath + sku.photoPath + "40_40_" + sku.photoName + '" alt="' + values[j] + '"/>');
          html.push('<p><span>' + values[j] + '</span></p></a>');
        }

      }
      html.push('</ol></dd></dl>');
    }
    var skuObj = $(html.join(""));

    var _checkDisabledSkuAttrValue = function (prevPrdSkuIds, nextAttrSkuDom) {
      var _strPrdSkuIds = nextAttrSkuDom.attr('data-skuId');
      var result = false;
      for (var i = 0, length = prevPrdSkuIds.length; i < length; i++) {
        if (_strPrdSkuIds.indexOf(prevPrdSkuIds[i] + "") > -1) {
          result = true;
          break;
        }
      }
      return result;
    };
    var _listenerAttrSkuTrigger = function (skuObj) {
      var _interSectionPrdList = [];
      var _first = true;
      var _skuId = null;
      $.each(skuObj.find("li.selected"), function () {
        var $li = $(this);
        var key = $li.find('a').attr('title');
        var nextAttrSkuDom = $li.closest('dl').next().find('li');
        if (_first) {
          _interSectionPrdList = _attrValue2SkuId[key];
          //决定下一sku属性可能不能选择
          $.each(nextAttrSkuDom, function () {
            var current = $(this);
            if (!_checkDisabledSkuAttrValue(_interSectionPrdList, current)) {
              current.addClass('disabled').removeClass('selected');
            } else {
              current.removeClass('disabled');
            }
          });
          _first = false;
          _skuId = (_preSku || ec.product.defaultSku);
          return;
        }
        var _arrTempSkuIds = [];
        var _tempList = _attrValue2SkuId[key];
        for (var i = 0; i < _interSectionPrdList.length; i++) {
          for (var j = 0; j < _tempList.length; j++) {
            if (_interSectionPrdList[i] == _tempList[j]) {
              _arrTempSkuIds.push(_interSectionPrdList[i]);
            }
          }
        }
        _interSectionPrdList = _arrTempSkuIds;
        //当attrSku中没有选完
        if (_interSectionPrdList.length != 1) {
          _skuId = (_preSku || ec.product.defaultSku);
          if (_interSectionPrdList.length > 1) {
            $.each(nextAttrSkuDom, function () {
              var current = $(this);
              if (!_checkDisabledSkuAttrValue(_interSectionPrdList, current)) {
                current.addClass('disabled').removeClass('selected');
              } else {
                current.removeClass('disabled');
              }
            });
          }
        } else {
          $.each(nextAttrSkuDom, function () {
            var current = $(this);
            if (!_checkDisabledSkuAttrValue(_interSectionPrdList, current)) {
              current.addClass('disabled').removeClass('selected');
            } else {
              current.removeClass('disabled');
            }
          });
          _skuId = _interSectionPrdList[0];
        }

      });
      return _skuId;
    };
    skuObj.find(".sku").click(function () {
      var thix = $(this).parent();
      //已禁用的不能点击
      if (thix.hasClass("disabled")) return false;

      var attrIds = thix.attr("data-attrId").split(","),
        attrName = thix.attr("data-attrName"),
        skuIds = [];

      for (var i = 0; i < attrIds.length; i++) {
        skuIds.push(_skuAttrId2SkuMap[attrIds[i]]);
      }
      //设置选中的属性值
      _selectAttrMap[attrName] = skuIds;

      //给属性sku添加选中样式
      thix.addClass("selected").siblings().removeClass("selected");
      $("#layoutRelative p a").each(function () {
        var tab = $(this).css('display');
        if (tab != 'none') {
          $(this).addClass('selected').siblings().removeClass('selected');
          return false;
        }
      })
      //每次点击都应该触发一个事件，来计算用出有这些选中共同属性的skuID的商品
      var _skuId = _listenerAttrSkuTrigger(skuObj);
      var firstLi = null;

      var flag = true;
      $.each(skuObj.find("ul"), function () {
        var $ol = $(this);
        if (1 != $ol.find("li.selected").length) {
          firstLi = $ol.find("li").not($ol.find("li.disabled")).first();
          if (firstLi.length >= 1) {
            flag = false;
            return false;
          }
        }
      });


      if (flag) {
        sku = _skuMap[_skuId];
        $('.product-operation-main').removeClass('product-operation-location');
        _updateSkuInfo();
        _updateSelect();


        var rightHeight = $('.product-property').height();
        if (rightHeight <= 526) {
          $('.product-operation-main').addClass('product-operation-location');
        } else {
          $('.product-operation-main').removeClass('product-operation-location');
        }
        isFirstIn = false;
      } else if (firstLi) {
        if (!isFirstIn) {
          $(firstLi).find(".sku").trigger("click");
        }
      }
    });

    //如果热销榜单为0 则不显示
    if ($('.hot-area').find("li").size() == 0) {
      $('.hot-area').hide();

      $("#pro-seg-hot").hide();
    }

    $("#pro-skus").html(skuObj);

    //服务说明----start

    html = [], skuId = ec.product.getSku();
    sku = ec.product.getSkuInfo(skuId);
    if (ec.product.seCode != ec.product.productSeCode) {
      html.push('已包邮<em></em>' + ec.product.productshopName + '发货，并提供售后服务');
    } else {
      if (parseFloat(ec.product.deliveryModeValueFreeBase) > 0 && ec.product.productType == 0) {
        if (sku.priceMode != 2) {
          if (parseFloat(sku.price) >= parseFloat(ec.product.deliveryModeValueFreeBase)) {
            html.push('已满' + ec.product.deliveryModeValueFreeBase + '元已免运费<em></em>');
          } else {
            html.push('满' + ec.product.deliveryModeValueFreeBase + '元即免运费，快去凑单吧<em></em>');
          }
        }
      }
      html.push('由华为商城负责发货，并提供售后服务');

    }
    $("#service-description").html(html.join(" "));
    //服务说明----end

    //促销消息
    html = [], htmldetail = []

    var isShowPromotions = false,
      isShowGifts = false;
    if (!sku.promotionLst || sku.promotionLst.length == 0) {
      $("#pro-promotions-list").html("");
      $("#pro-promotions-list").hide();
      $("#pro-promotions-list-detail").hide();
      $("#pro-promotions-list-detail").html('');
    } else {
      for (var i = 0; i < sku.promotionLst.length; i++) {
        html.push('<li><strong></strong><span>' + sku.promotionLst[i].promoLabel + '</span>');
        html.push('</li>');
        htmldetail.push('<li><strong></strong><span>' + sku.promotionLst[i].promoLabel + '</span><p>' + sku.promotionLst[i].ruleDescription);
        //需要实名认证
        if (sku.promotionLst[i].isRealNameAuth == "1") {
          htmldetail.push('<a href="/authmember/accesstoken" target="_blank">&nbsp;限实名用户参加 ></a>');
        }
        htmldetail.push('</p>');
        htmldetail.push('</li>')
      }
      $("#pro-promotions-list").html(html.join(""));
      $("#pro-promotions-list-detail").html(htmldetail.join(""));
      isShowPromotions = true;
      //#pro-promotions-list下面的li标签只显示三个 超过的隐藏
      $('#pro-promotions-list li').hide();
      for (var i = 0; i < 3; i++) {
        $('#pro-promotions-list li').eq(i).show();
      }
      $("#pro-promotions-list").show();
      $("#pro-promotions-list-detail").show();
    }


    if (skuObj.find(".sku").length == 0) {
      var sku = ec.product.getSku();
      packFlag = false;
      sku = ec.product.getSkuInfo(sku);
      upDownButton = "";
      ec.product.getFeature(sku.id);
      ec.product.getParameter(sku.id, sku.code);
      ec.product.getPackageAndService(sku.id);
      ec.product.processSupportDisplayDilieryTime(sku);
    }


    //选中默认的SKU属性
    ec.product.selectBySku(ec.product.setSkuId || ec.product.defaultSku);
    var skuIdForGift = ec.product.setSkuId || ec.product.defaultSku,
      skuForPromotion, showPromotion = false,
      showGifts = false;
    skuForPromotion = ec.product.getSkuInfo(skuIdForGift);

    if (!skuForPromotion.promotionLst || skuForPromotion.promotionLst.length == 0) {
      showPromotion = false;
    } else {
      showPromotion = true;
    }
    if (!skuForPromotion.giftList || skuForPromotion.giftList.length == 0) {
      showGifts = false;
    } else {
      showGifts = true;
    }
    if (!showPromotion) {
      $("#pro-promotions-list").html("");
      $("#pro-promotions-list").hide();
    }
    if (showGifts) {
      $("#pro-gift").show();
      $("#pro-gift-list-select").html(ec.product.gift.ftl(ec.product.getSku()));
    } else {
      $("#pro-gift").hide();
    }

    //套图切换
    $("#pro-gallerys").find("img").mouseover(_proGallerysMouseOver);

    var paras = getUrlParaMap4CartBinding();
    var isSuccess = paras["isSuccess"];
    if (null != isSuccess && "0" == isSuccess) {
      bindCartResult("ec-binding-phone");
    }


    //鼠标获得地址焦点时，预加载地址相关信息
    $("#address").hover(
      function () {
        //取得SKU
        var sku = ec.product.getSku();
        sku = ec.product.getSkuInfo(sku);
        //预加载用户收货地址及省市区相关地址信息
        ec.product.processAddress(sku);
      },
      function () {
        //鼠标离开详细地址信息
      });

    //判断是否有套餐
    if ($("#product-package-area:has(li)").length == 0) {
      $("#product-package-area").hide();
    }

  });
})();


ec.product.disableAddCartButtons = function () {
  $('#pro-operation a.product-button01').each(function () {
    $(this).removeClass("product-button01").addClass("product-button01 disabled");
    this.backup = this.onclick;
    this.onclick = '';
  });

  $('#pro-operation a.button-book-2').each(function () {
    $(this).removeClass("pro-button01 button-style-2").addClass("pro-button01 button-style-disabled-2");
    this.backup = this.onclick;
    this.onclick = '';
  });
  $('a.button-add-cart-2, a.button-add-cart-3').each(function () {
    $(this).removeClass("pro-button01 button-style-1").addClass("pro-button01 button-style-disabled-2");
    this.backup = this.onclick;
    this.onclick = '';
  });
};

ec.product.enableAddCartButtons = function () {
  $('#pro-operation a.product-button01').each(function () {
    $(this).removeClass("product-button01 disabled").addClass("product-button01")
      .css('background-position-y', '8px');
    this.onclick = this.backup;
    this.backup = '';
  });

  $('#pro-operation a.button-book-2').each(function () {
    $(this).removeClass("pro-button01 button-style-disabled-2").addClass("pro-button01 button-style-2");
    this.onclick = this.backup;
    this.backup = '';
  });

  $('a.button-add-cart-2, a.button-add-cart-3').each(function () {
    $(this).removeClass("pro-button01 button-style-disabled-2").addClass("pro-button01 button-style-1");
    this.onclick = this.backup;
    this.backup = '';
  });
};

//加入购物车
ec.product.addCart = function () {
  var buyNumber = parseInt($("#pro-quantity").val()),
    cartNUmber = parseInt($('#header-cart-total').html());
  $('#header-cart-total').html(cartNUmber + buyNumber);
  _paq.push(['trackLink', 'Click PC_addtocart_btn', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });
  // 加入必选判断  防止买错
  var skusListArr = $("#pro-skus").find("dl");
  for (p = 0; p < skusListArr.length; p++) {
    var flag = false;
    var skuInfoArr = skusListArr.get(p);
    $(skuInfoArr).children('.product-choose-detail').children('ul').find('li').each(function (index) {
      if ($(this).hasClass("selected")) {
        flag = true;
        return;
      }
    });
    if (!flag) {
      alert("请选择需要购买的类型");
      return false;
    }
  }

  ec.product.disableAddCartButtons();

  //定义添加到购物车的ajax的参数
  var paras;
  //商品skuId
  var skuId = ec.product.getSku();
  //购买数量
  var buyNum = $("#pro-quantity").val();
  //itemType类型

  var type = ec.cart.productTypeCorrespondence(ec.product.productType);
  //延保
  var extendServiceSkuID = $("#extendSelect").attr("skuid");
  //意外保
  var accidentServiceSkuID = $("#accidentSelect").attr("skuid");
  //赠品
  var finalGift = ec.product.gift.finalMainSbomGiftMap[skuId];
  var cartjson = '';

  var gifts = [];
  // cart使用
  var gifts2Cart = "";
  // order使用
  var gifts2Order = [];

  var temp = ec.product.finalGift();

  paras = {
    salePortal: 1, //销售前端 1、web 2、wap 3、app
    saleChannel: 1001, //销售渠道
    needResultset: 0,
    cartjson: temp.cartjson
  };

  var orderItemReqArgList = [];
  var orderitem = {};
  var gifts2Order = temp.gifts2Order;
  orderitem.itemId = $("#pro-sku-code").val();
  orderitem.qty = $("#pro-quantity").val();
  orderitem.itemType = 'S0';

  orderitem.gifts = gifts2Order;

  orderItemReqArgList.push(orderitem);
  var extendSbomCode = $("#extendSelect").attr("data-scode");
  var accidentSbomCode = $("#accidentSelect").attr("data-scode");

  //获取页面中选中的服务商品的skuCode，并构成参数数组
  var extendSkuCodes = [],
    extendItem = {},
    accidentItem = {};
  if (extendSbomCode.length > 0) {
    extendItem.itemId = extendSbomCode;
    extendItem.qty = $('#pro-quantity').val();
    extendItem.itemType = 'S1';
    extendItem.itemProp = {
      'main_skucode': $('#pro-sku-code').val()
    };
    orderItemReqArgList.push(extendItem);
    if (accidentSbomCode.length > 0) {
      accidentItem.itemId = accidentSbomCode;
      accidentItem.qty = $('#pro-quantity').val();
      accidentItem.itemType = 'S6';
      accidentItem.itemProp = {
        'main_skucode': $('#pro-sku-code').val()
      };
      orderItemReqArgList.push(accidentItem);
    }
  } else {
    if (accidentSbomCode.length > 0) {
      accidentItem.itemId = accidentSbomCode;
      accidentItem.qty = $('#pro-quantity').val();
      accidentItem.itemType = 'S6';
      accidentItem.itemProp = {
        'main_skucode': $('#pro-sku-code').val()
      };
      orderItemReqArgList.push(accidentItem);
    }
  }

  var jsonReqArg = ec.lang.json.stringify(orderItemReqArgList);

  ec.cart.add(paras, {
    successFunction: function (json) {
      if (json.retcode == 0) {
        var cartInfo = json.cartInfo;

        $('#cart-tips').show();
        $('#cart-tips').find('p').html($("#pro-name").text());
        $('.pro-add-success-total').hide();
        $('#header-cart-total').html(json.cartNumber);
      }
      ec.product.enableAddCartButtons();
    },
    errorFunction: function (json) {
      //alert(json.msg);
      $('#popup-tips-msg').html(json.msg);
      $('#popup-tips').show();
      ec.product.enableAddCartButtons();
    }
  });
  //	点击弹窗外区域时,弹窗消失
  ec.product.clickHide = function (id) {
    $(document).click(function () {
      $("#" + id).hide();
    });
    $('#' + id).click(function (event) {
      event.stopPropagation();
    })
  };
  ec.product.clickHide('cart-tips');
};
/**
 * 检测商品是否有延保意外保和赠品
 */
ec.product.finalGift = function () {
  var temp = '';
  var cartjson = '';
  //商品skuId
  var skuId = ec.product.getSku();
  //购买数量
  var buyNum = $("#pro-quantity").val();
  //延保
  var extendServiceSkuID = $("#extendSelect").attr("skuid");
  //意外保
  var accidentServiceSkuID = $("#accidentSelect").attr("skuid");

  //赠品
  var finalGift = ec.product.gift.finalMainSbomGiftMap[skuId];
  var gifts = [];
  // cart使用
  var gifts2Cart = [];
  // order使用
  var gifts2Order = [];
  // 如果有赠品
  if (finalGift) {
    for (var key in finalGift) {
      var aGift = {
        "sbomCode": finalGift[key].giftSkuCode
      };
      var bGift = {
        "sbomCode": finalGift[key].giftSkuId
      };
      gifts2Cart.push(bGift);
      gifts2Order.push(aGift);
    }
    //单品+延保意外保
    if (extendServiceSkuID.length > 0 && accidentServiceSkuID.length > 0) {
      cartjson = JSON.stringify([{
          "itemId": extendServiceSkuID,
          "mainItemId": skuId,
          "itemType": "S1",
          "qty": buyNum
        },
        {
          "itemId": accidentServiceSkuID,
          "mainItemId": skuId,
          "itemType": "S6",
          "qty": buyNum
        },
        {
          "itemId": skuId,
          "itemType": "S0",
          "qty": buyNum,
          "gifts": gifts2Cart
        }
      ]);
    } else {
      if (extendServiceSkuID.length > 0) { //单品+延保
        cartjson = JSON.stringify([{
            "itemId": extendServiceSkuID,
            "mainItemId": skuId,
            "itemType": "S1",
            "qty": buyNum
          },
          {
            "itemId": skuId,
            "itemType": "S0",
            "qty": buyNum,
            "gifts": gifts2Cart
          }
        ]);
      } else if (accidentServiceSkuID.length > 0) { //单品 +意外保
        cartjson = JSON.stringify([{
            "itemId": accidentServiceSkuID,
            "mainItemId": skuId,
            "itemType": "S6",
            "qty": buyNum
          },
          {
            "itemId": skuId,
            "itemType": "S0",
            "qty": buyNum,
            "gifts": gifts2Cart
          }
        ]);
      } else { //单品+赠品
        cartjson = JSON.stringify([{
          "itemId": skuId,
          "itemType": "S0",
          "qty": buyNum,
          "gifts": gifts2Cart
        }]);
      }
    }
  } else {
    //单品+延保意外保
    if (extendServiceSkuID.length > 0 && accidentServiceSkuID.length > 0) {
      cartjson = JSON.stringify([{
          "itemId": extendServiceSkuID,
          "mainItemId": skuId,
          "itemType": "S1",
          "qty": buyNum
        },
        {
          "itemId": accidentServiceSkuID,
          "mainItemId": skuId,
          "itemType": "S6",
          "qty": buyNum
        },
        {
          "itemId": skuId,
          "itemType": "S0",
          "qty": buyNum
        }
      ]);
    } else {
      if (extendServiceSkuID.length > 0) { //单品+延保
        cartjson = JSON.stringify([{
            "itemId": extendServiceSkuID,
            "mainItemId": skuId,
            "itemType": "S1",
            "qty": buyNum
          },
          {
            "itemId": skuId,
            "itemType": "S0",
            "qty": buyNum
          }
        ]);
      } else if (accidentServiceSkuID.length > 0) { //单品 +意外保
        cartjson = JSON.stringify([{
            "itemId": accidentServiceSkuID,
            "mainItemId": skuId,
            "itemType": "S6",
            "qty": buyNum
          },
          {
            "itemId": skuId,
            "itemType": "S0",
            "qty": buyNum
          }
        ]);
      } else { //单品
        cartjson = JSON.stringify([{
          "itemId": skuId,
          "itemType": "S0",
          "qty": buyNum
        }]);
      }
    }
  }
  temp = {
    cartjson: cartjson,
    gifts2Order: gifts2Order
  }
  return temp;
};

//后壳定制服务立即下单cover
ec.product.orderNowCover = function () {

  ec.account.afterLogin(function () {

    //ec.track(["/product/buyType" , "direct"]);
    // 加入必选判断  防止买错
    var skusListArr = $("#pro-skus").find("dl");
    for (p = 0; p < skusListArr.length; p++) {
      var flag = false;
      var skuInfoArr = skusListArr.get(p);
      $(skuInfoArr).children('.product-choose-detail').children('ul').find('li').each(function (index) {
        if ($(this).hasClass("selected")) {
          flag = true;
          return;
        }
      });

      if (!flag) {
        alert("请选择需要购买的类型");
        return false;
      }
    }

    ec.product.disableAddCartButtons();

    //单品skuCode
    var sbomCode;
    //单品数量
    var quantity;
    //延保
    var extendServiceSKU;
    //意外保险
    var exceptionServiceSKU;

    //定义所有商品（单品+服务商品）的SkuId数组
    var extendSkuIds = [];
    //将单品的skuId赋值给allSkuIds数组的第一个元素
    sbomCode = ec.product.getSku();
    sbomCode = $("#pro-sku-code").val();

    //单品的数量
    quantity = $("#pro-quantity").val();

    //获取页面中选中的服务商品的skuId，并构成参数数组
    //		var $extendList = $("ul>li.selected>div.sku");
    //	        for(var i=0;i<$extendList.length;i++){
    //	        	extendSkuIds[i]=$($extendList[i]).attr("title");
    //	         }
    //判断用户是否选择了延保商品
    //	    if($("#extendProtected").hasClass("selected")){
    //	    	extendServiceSKU = extendSkuIds[0];
    //	    	//判断用户是否选择了意外保商品
    //	    	 if($("#accidentProtected").hasClass("selected")){
    //	    		exceptionServiceSKU = extendSkuIds[1];
    //	    	    }
    //	    }else{
    //	   	 if($("#accidentProtected").hasClass("selected")){
    //	   		    exceptionServiceSKU = extendSkuIds[0];
    //	   	    }
    //	    }


    extendServiceSKU = $("#extendSelect").attr("skuid");
    exceptionServiceSKU = $("#accidentSelect").attr("skuid");


    var input = "";

    input = '<input name="sbomCode" type="text" value="' + sbomCode + '">';
    input += '<input name="quantity" type="text" value="' + quantity + '">';
    if (extendServiceSKU) {
      input += '<input name="extendServiceSKU" type="text" value="' + extendServiceSKU + '">';
    }
    if (exceptionServiceSKU) {
      input += '<input name="exceptionServiceSKU" type="text" value="' + exceptionServiceSKU + '">';
    }
    input += '<input name="state" type="text" value="0">';

    var form = gid("order-cover-form");
    form.innerHTML = input;

    //判断用户是否绑定手机
    ec.binding.isBindedMobileOrEnterpriseUser(function () {
      setTimeout(function () {
        form.action = domainMain + "/uidesign/edit";
        form.submit();
      }, 500);
    });

  });
};

//优享购
ec.product.orderEasyBuy = function () {

  _paq.push(['trackLink', 'Click PC_buynow_btn', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });

  //最新的状态为已登录
  if (ec.account.isLogin()) {


    //ec.track(["/product/buyType" , "direct"]);
    // 加入必选判断  防止买错
    var skusListArr = $("#pro-skus").find("dl");
    for (p = 0; p < skusListArr.length; p++) {
      var flag = false;
      var skuInfoArr = skusListArr.get(p);
      $(skuInfoArr).children('.product-choose-detail').children('ul').find('li').each(function (index) {
        if ($(this).hasClass("selected")) {
          flag = true;
          return;
        }
      });

      if (!flag) {
        alert("请选择需要购买的类型");
        return false;
      }
    }

    ec.product.disableAddCartButtons();

    var skuId = ec.product.getSku();
    var skuInfo = ec.product.getSkuInfo(skuId);
    var finalGift = ec.product.gift.finalMainSbomGiftMap[skuId];

    var skuCode = $("#pro-sku-code").val(),
      extendCode = $("#extendSelect").attr("data-scode"),
      accidentCode = $("#accidentSelect").attr("data-scode"),
      giftCodes = "";


    if (finalGift) {
      var giftCodeList = [];
      for (var key in finalGift) {
        giftCodeList.push(finalGift[key].giftSkuCode);
      }
      giftCodes = giftCodeList.join(",");
    }

    window.location.href = "/order/confirmEasybuy?routingTag=26&skuCode=" +
      skuCode +
      "&extendCode=" + extendCode +
      "&accidentCode=" + accidentCode +
      "&giftCodes=" + giftCodes +
      "&productId=" + ec.product.id +
      "&skuId=" + skuId +
      "&_t=" + new Date().getTime();


  } else {
    //如果未登录，则跳转到登录页面
    var targetURL = domainMain + "/account/login?url=" +
      encodeURIComponent(window.location.pathname + "#" + rush.sbom.getCurrSkuId()) +
      "&_t=" + new Date().getTime();
    //跳转到登录页面，登录成功后跳转到本页面
    window.location.href = targetURL;
  }
}
//是否存在有效的优享购
ec.product.isEasyBuy = function () {
  //当前skuInfo
  var skuInfo = ec.product.getSkuInfo(ec.product.getSku());

  //优购码购买方式不展示优享购
  var isPriority = $("#isPriority").val();
  var isPrioritySku = ec.product.getSkuPriority(ec.product.getSku());
  if (isPriority == 1 && isPrioritySku == true) {
    return false;
  }
  if (skuInfo && skuInfo.showEasyBuy == "1") {
    return true;
  }
  return false;
}

//立即下单
ec.product.orderNow = function () {

  _paq.push(['trackLink', 'Click PC_buynow_btn', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });
  ec.account.afterLogin(function () {

    //ec.track(["/product/buyType" , "direct"]);
    // 加入必选判断  防止买错
    var skusListArr = $("#pro-skus").find("dl");
    for (p = 0; p < skusListArr.length; p++) {
      var flag = false;
      var skuInfoArr = skusListArr.get(p);
      $(skuInfoArr).children('.product-choose-detail').children('ul').find('li').each(function (index) {
        if ($(this).hasClass("selected")) {
          flag = true;
          return;
        }
      });

      if (!flag) {
        alert("请选择需要购买的类型");
        return false;
      }
    }

    ec.product.disableAddCartButtons();

    var orderItemReqArgList = [];
    var orderitem = {};

    orderitem.itemId = $("#pro-sku-code").val();
    orderitem.qty = $("#pro-quantity").val();
    orderitem.itemType = 'S0';
    // 赠品
    var finalGift = ec.product.gift.finalMainSbomGiftMap[ec.product.getSku()];
    if (finalGift) {
      var gifts2Order = [];
      for (var key in finalGift) {
        var aGift = {
          "sbomCode": finalGift[key].giftSkuCode
        };
        gifts2Order.push(aGift);
      }

      orderitem.gifts = gifts2Order;
    }

    orderItemReqArgList.push(orderitem);

    //获取页面中选中的服务商品的skuCode，并构成参数数组
    var extendSbomCode = $("#extendSelect").attr("data-scode");
    var accidentSbomCode = $("#accidentSelect").attr("data-scode");

    var extendSkuCodes = [],
      extendItem = {},
      accidentItem = {};
    if (extendSbomCode.length > 0) {
      extendSkuCodes[0] = extendSbomCode;
      if (accidentSbomCode.length > 0) {
        extendSkuCodes[1] = accidentSbomCode;
      }
    } else {
      if (accidentSbomCode.length > 0) {
        extendSkuCodes[0] = accidentSbomCode;
      }
    }

    var extendItem = {};
    var accidentItem = {};
    if (extendSbomCode.length > 0) {
      extendItem.itemId = extendSkuCodes[0];
      extendItem.qty = $('#pro-quantity').val();
      extendItem.itemType = 'S1';
      extendItem.itemProp = {
        'main_skucode': $('#pro-sku-code').val()
      };
      orderItemReqArgList.push(extendItem);
      if (accidentSbomCode.length > 0) {
        accidentItem.itemId = extendSkuCodes[1];
        accidentItem.qty = $('#pro-quantity').val();
        accidentItem.itemType = 'S6';
        accidentItem.itemProp = {
          'main_skucode': $('#pro-sku-code').val()
        };
        orderItemReqArgList.push(accidentItem);
      }
    } else {
      if (accidentSbomCode.length > 0) {
        accidentItem.itemId = extendSkuCodes[0];
        accidentItem.qty = $('#pro-quantity').val();
        accidentItem.itemType = 'S6';
        accidentItem.itemProp = {
          'main_skucode': $('#pro-sku-code').val()
        };
        orderItemReqArgList.push(accidentItem);
      }
    }

    var jsonReqArg = ec.lang.json.stringify(orderItemReqArgList);

    var input = "";
    input += '<input name="orderReqJson" type="text" value='
    '+ jsonReqArg +'
    '>';
    input += '<input name="state" type="text" value="0">';
    var form = gid("order-confirm-form");
    form.innerHTML = input;

    //判断用户是否绑定手机
    ec.binding.isBindedMobileOrEnterpriseUser(function () {
      setTimeout(function () {
        form.submit();
      }, 500);
    });
  });
};


//加入购物车 - 登录
ec.product.addCartWithLogin = function () {
  ec.account.afterLogin(ec.product.addCart);
};

//购买组合套装
ec.product.buyBundle = function (bundleId) {
  ec.product.disableAddCartButtons();

  var cartjson = JSON.stringify([{
    "itemId": bundleId,
    "itemType": "B",
    "qty": 1
  }]);
  var paras = {
    saleChannel: 1001,
    salePortal: 1,
    needResultset: 0,
    cartjson: cartjson

  };

  var orderItemReqArgList = '[{"itemId":' + bundleId + ',"qty":1,"itemType":"B"}]';

  ec.cart.add(paras, {
    successFunction: function (json) {
      ec.product.enableAddCartButtons();
      $("#order-shoppingCart-form").submit();
    },
    errorFunction: function (json) {
      ec.product.enableAddCartButtons();
      alert(json.msg);
    }
  });
  _paq.push(['trackLink', 'Click PC_addtocart_btn', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });
};

ec.product.buyComb = function () {

  var orderItemReqArgList = [];

  var id = ec.product.getSku(),
    skuIds = [id],
    quantity = [1],
    type = [1],
    isPriority = $("#isPriority").val();

  var mainItem = {};
  mainItem.itemId = $("#pro-sku-code").val();;
  mainItem.qty = 1;
  mainItem.itemType = 'S0';
  orderItemReqArgList.push(mainItem);
  var comboToCart = [];
  var mainProduct = {
    "itemId": id,
    "itemType": "S0",
    "qty": 1
  };
  comboToCart.push(mainProduct);
  $('[id="comb-pro-' + id + '"]').find("input[name=skuId]:checked").each(function () {
    skuIds.push(this.value);
    quantity.push(1);
    type.push(1);

    var orderitem = {};
    orderitem.itemId = $(this).attr("data-scode");
    orderitem.qty = 1;
    orderitem.itemType = 'S0';
    orderItemReqArgList.push(orderitem);
    //获取选中的skuId
    var combo = {
      "itemType": "S0",
      "qty": 1,
      "itemId": this.value
    };
    comboToCart.push(combo);
  });
  var paras = {
    saleChannel: 1001,
    salePortal: 1,
    needResultset: 0,
    cartjson: JSON.stringify(comboToCart)
  };
  if (isPriority == 1) {
    if (ec.product.getSkuPriority(id) == true) {
      return ec.product.buy("sku", skuIds);
    }
  }
  $("#order-confirm-form").attr({
    "action": "/order/nowConfirmcart",
    "method": "post"
  });

  ec.product.disableAddCartButtons();

  var jsonReqArg = ec.lang.json.stringify(orderItemReqArgList);

  ec.cart.add(paras, {
    successFunction: function (json) {
      ec.product.enableAddCartButtons();
      $("#order-shoppingCart-form").submit();
    },
    errorFunction: function (json) {
      ec.product.enableAddCartButtons();
      alert(json.msg);
    }
  });
};

//立即购买
ec.product.buy = function (type, id) {
  //BI上报
  _paq.push(['trackLink', '立即购买', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });

  ec.account.afterLogin(function () {

    var input = "";
    if (type == "sku") {
      var orderItemReqArgList = [];
      var orderitem = {};

      orderitem.itemId = $("#pro-sku-code").val();
      orderitem.qty = 1;
      orderitem.itemType = 'S0';

      //赠品
      var finalGift = ec.product.gift.finalMainSbomGiftMap[ec.product.getSku()];
      // 如果有赠品
      if (finalGift) {
        // order使用
        var gifts2Order = [];
        for (var key in finalGift) {
          var aGift = {
            "sbomCode": finalGift[key].giftSkuCode
          };
          gifts2Order.push(aGift);
        }
        orderitem.gifts = gifts2Order;
      }

      orderItemReqArgList.push(orderitem);

      var jsonReqArg = ec.lang.json.stringify(orderItemReqArgList);

      input = '<input name="orderReqJson" type="text" value='
      '+ jsonReqArg +'
      '>';
    }

    var form = gid("order-confirm-form");
    form.innerHTML = input;

    //判断用户是否绑定手机
    ec.binding.isBindedMobileOrEnterpriseUser(function () {
      setTimeout(function () {
        form.submit();
      }, 500);
    });
  });
};

//定时抢购
ec.product.timingBuy = function () {
  var getSku = ec.product.getSkuInfo(ec.product.getSku() || ec.product.defaultSku);

  //获取服务器当前时间
  var _now = ec.product.getSysDate();

  //抢购开始时间
  var start = getSku.startTime;
  var startTime = new Date();
  startTime.setTime(start.parseDate('yyyy-MM-dd HH:mm:ss'));
  var startArray = [];
  startArray.push(start);

  //抢购倒计时提前时间
  var countdownLength = getSku.countDown;

  $("#pro-operation").css("visibility", "visible");
  $("#product-operation").show(); //console.log("product-operation.show()");

  //抢购已经开始
  if ((_now - startTime) >= 0) {
    // 抢购结束时间
    var end = getSku.endTime;
    var endTime = new Date();
    if (null == end || '' == end) {
      endTime = new Date(2999, 1, 1, 0, 0, 0);
    } else {
      endTime.setTime(end.parseDate('yyyy-MM-dd HH:mm:ss'));
    }
    // endtime为空时，默认活动时间超长，兼容原逻辑
    // Endtime is null? endtime=”2999-01-01 00:00:00?:endtime
    if ((_now - endTime) < 0) {
      // 有库存，展示加入购物车
      var haveQuantity = ec.product.inventory.haveInventory(getSku.id)
      if (haveQuantity) {
        var content = '<a href="javascript:;" onclick="ec.product.addCart()" class="product-button01" ><span>加入购物车</span></a>' +
          '<a href="javascript:;" onclick="ec.product.orderNow()" class="product-button02" ><span>立即下单</span></a>' +
          '<span class="product-button-tips">限时抢购进行中</span>';
        $("#pro-operation").html(content);

        $("#product-operation").show();
      } else {
        // 无库存，展示“到货通知”
        $("#pro-quantity-area").hide();
        $("#pro-operation")
          .html('<a href="javascript:;" class="product-button02" onclick="ec.product.arrival()"><span>到货通知</span></a>');

        $("#product-operation").show();

      }
    } else {
      // 当前时间小于结束时间，则活动结束，展示活动结束按钮
      $("#pro-operation").html('<a href="javascript:;" class="product-button02 disabled">活动已结束</a>');
      $("#pro-operation").css("visibility", "visible");
      $("#product-operation").show();
    }

  }
  //开售提醒时间
  else if (!ec.util.isEmpty(getSku.gotoUrl) && ((startTime - _now) / (1000 * 3600) > countdownLength)) {
    if (1 == getSku.isShowReminder) {
      $("#pro-operation").html('<a target="_blank" href="' + getSku.gotoUrl + '" class="product-button02" ><span>开售提醒</span></a>');
      $("#product-operation").show(); //console.log("product-operation.show()");
    } else if (0 == getSku.isShowReminder) {
      var content = '<a href="javascript:;" class="product-button01 disabled" ><span>加入购物车</span></a>' +
        '<a href="javascript:;"  class="product-button02 disabled" ><span>立即下单</span></a><div class="product-time"></div>';
      $("#pro-operation").html(content);
      $("#product-operation").show();

      //倒计时
      ec.ui.countdown2($('.product-time'), {
        html: '<p>离抢购开始还有：</p><ul><li><span>{#day}</span></li><li><em>天</em></li><li><span>{#hours}</span></li><li><em>:</em></li><li><span>{#minutes}</span></li><li><em>:</em></li><li><span>{#seconds}</span></li>',
        now: _now,
        times: startArray,
        callback: function (json) {
          var content = '<a href="javascript:;" onclick="ec.product.addCart()" class="product-button01" ><span>加入购物车</span></a>' +
            '<a href="javascript:;" onclick="ec.product.orderNow()" class="product-button02" ><span>立即下单</span></a>';
          $("#pro-operation").html(content);
          $("#product-operation").show();
        }
      });
    }
  }
  //抢购倒计时时间
  else {
    var content = '<a href="javascript:;" class="product-button01 disabled" ><span>加入购物车</span></a>' +
      '<a href="javascript:;"  class="product-button02 disabled" ><span>立即下单</span></a><div class="product-time"></div>';
    $("#pro-operation").html(content);
    $("#product-operation").show(); //console.log("product-operation.show()");
    //倒计时
    ec.ui.countdown2($('.product-time'), {
      html: '<p>离抢购开始还有：</p><ul><li><span>{#day}</span></li><li><em>天</em></li><li><span>{#hours}</span></li><li><em>:</em></li><li><span>{#minutes}</span></li><li><em>:</em></li><li><span>{#seconds}</span></li>',
      now: _now,
      times: startArray,
      callback: function (json) {
        var content = '<a href="javascript:;" onclick="ec.product.addCart()" class="product-button01" ><span>加入购物车</span></a>' +
          '<a href="javascript:;" onclick="ec.product.orderNow()" class="product-button02" ><span>立即下单</span></a>';
        $("#pro-operation").html(content);
        $("#product-operation").show();
      }
    });
  }

};



//到货通知
ec.product.arrival = function () {
  ec.account.afterLogin(function () {
    //更新用户信息
    ec.product.syncCustomSession();
    var email = ec.product.email;
    var mobile = ec.product.mobile;
    //到货通知方式
    var noticeType = "";

    var box = new ec.box($("#product-arrival-html").val(), {
      boxid: "product-arriva-box",
      boxclass: "ol_box_4",
      title: "到货通知",
      showButton: false,
      onopen: function (box) {

        //判断用户是否已经绑定邮箱或手机号码
        if (ec.util.isEmpty(email)) {
          $('#arrival-email').css({
            'cursor': 'pointer'
          });
          $('#arrival-email').click(function () {
            window.open("/member/account");
            ec.product.bind();
          })
          $("#arrival-email").attr('class', 'disabled');
          $("#account-email").html('未绑定安全邮箱&nbsp;<a href="javascript:;" target="_blank">去绑定</a>');
        } else {
          $("#arrival-email").bind("click", function () {
            noticeType = ec.product.chooseNoticeType('email');
          });
          $("#account-email").html(email);
        }

        if (ec.util.isEmpty(mobile)) {
          $('#arrival-mobile').css({
            'cursor': 'pointer'
          });
          $('#arrival-mobile').click(function () {
            window.open("/member/account");
            ec.product.bind();
          })
          $("#arrival-mobile").attr('class', 'disabled');
          $("#account-mobile").html('未绑定安全手机&nbsp;<a href="javascript:;" target="_blank">去绑定</a>');
        } else {
          $("#arrival-mobile").bind("click", function () {
            noticeType = ec.product.chooseNoticeType('mobile');
          });
          $("#account-mobile").html(ec.product.splitMobile(mobile));
        }
      },
      onok: function (box) {

        //一个都没选
        if (noticeType.length == 0) {
          $("#arrival-error span").html("请选择一种通知方式！");
          $("#arrival-error").removeClass("hide");
          return;
        }

        //默认为邮件提醒
        var type = "1";
        var informWay = email;
        if (noticeType == "mobile") {
          type = "3";
          informWay = mobile;
        }

        //请求到货通知接口
        new ec.ajax().submit({
          url: "/product/arrivalMail.json",
          data: {
            informWay: informWay,
            type: type,
            skuId: ec.product.getSku()
          },
          timeout: 10000,
          timeoutFunction: function () {
            $("#arrival-error span").html("操作超时，请重试！");
            $("#arrival-error").removeClass("hide");
          },
          beforeSendFunction: ec.ui.loading.show,
          afterSendFunction: ec.ui.loading.hide,
          successFunction: function (json) {
            if (!json.success) {
              $("#arrival-error span").html(json.msg);
              $("#arrival-error").removeClass("hide");
              return;
            }
            alert("设置成功！");
            $("#arrival-error").addClass("hide");
            box.close();
            $(".ol_box_mask").remove();
          }
        });
      },
      onclose: function (box) {
        $(".ol_box_mask").remove();
      }
    });
    box.open();

    //点击去绑定的同时，关闭到货通知对话框
    ec.product.bind = function () {
      box.close();
      $(".ol_box_mask").remove();
    };
  });
};


//记录用户选择的通知方式
ec.product.chooseNoticeType = function (type) {

  //清除所有选中状态
  $("#arrival-email").removeClass("selected");
  $("#arrival-mobile").removeClass("selected");

  //选中选择的通知方式
  $("#arrival-" + type).attr('class', 'selected');

  return type;
};


//关注此商品
ec.product.attention = function () {
  var box = new ec.box($("#product-attention-html").val(), {
    boxid: "product-attention-box",
    title: "关注商品",
    width: 580,
    focus: "input[name=email]",
    showButton: false,
    onok: function (box) {
      var email = box.find("input[name=email]").val(),
        mobile = box.find("input[name=mobile]").val(),
        regMobile = /^0?(13|14|15|17|18)[0-9]{9}$/;


      if (!email) {
        alert("请输入email！");
        return;
      }
      if (!ec.util.isEmail(email)) {
        alert("请输入正确的email！");
        return;
      }

      if (!mobile) {
        alert("请输入手机号码！");
        return;
      }
      if (!regMobile.test(mobile)) {
        alert("请输入正确的手机号码！");
        return;
      }

      new ec.ajax().submit({
        url: "/product/saveAttention.json",
        data: {
          email: email,
          phone: mobile,
          skuId: ec.product.getSku()
        },
        timeout: 10000,
        timeoutFunction: function () {
          alert("操作超时，请重试！");
        },
        beforeSendFunction: ec.ui.loading.show,
        afterSendFunction: ec.ui.loading.hide,
        successFunction: function (json) {
          if (!json.success) {
            ec.showError(json);
            return;
          }
          alert("设置成功！");
          box.close();
        }

      });


    }
  });
  box.open();
  box.find("input[name=email]").focus();
};
//验证是否允许购买延保服务
ec.product.checkExtend = function () {
  var skuId = ec.product.getSku();
  val = $.trim($('#extend-text').val()),
    $succussMsg = $('#extend-msg-succuss'),
    $errorMsg = $('#extend-msg-error'),
    msgText = '<span class="fcn">*</span>&nbsp;',
    link = '';
  if (val.length > 5) {
    new ec.ajax().get({
      url: '/tcs/query.json?_t=' + (new Date()).getTime() + '&skuId=' + skuId + '&imei=' + val,
      timeout: 10000,
      timeoutFunction: function () {
        $("#pro-extend-result-id").removeClass("hide");
        $errorMsg.html(msgText + '操作超时，请重试！').show();
        $succussMsg.hide();
      },
      beforeSendFunction: function () {
        ec.ui.loading.show({
          modal: false
        });
      },
      afterSendFunction: ec.ui.loading.hide,
      successFunction: function (json) {

        if (!json.success) {
          if (json.otherPrdId) link = '&nbsp;&nbsp;<a href="/product/' + json.otherPrdId + '.html#' + json.otherSkuId + ',0">前去购买>></a>';
          $("#pro-extend-result-id").removeClass("hide");
          $errorMsg.html(msgText + json.msg + link).show();
          $succussMsg.hide();
          $('#button-extend').attr('class', 'pro-button01 button-style-disabled-1 button-go-extend-checkout-disabled');
          return;
        }
        $("#pro-extend-result-id").removeClass("hide");
        $succussMsg.html(msgText + json.msg).show();
        $errorMsg.hide();
        $('#button-extend').attr('class', 'pro-button01 button-style-1 button-go-extend-checkout');
      }
    });
  } else {
    $succussMsg.hide();
    $("#pro-extend-result-id").removeClass("hide");
    $errorMsg.html(msgText + '请输入正确的IMEI/SN/MEID信息').show();
    $('#button-extend').attr('class', 'pro-button01 button-style-disabled-1 button-go-extend-checkout-disabled');
  }
  return false;
};
//购买延保订单
ec.product.extendBuyNow = function () {
  //BI上报
  _paq.push(['trackLink', '延保商品 - 立即购买', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });
  $('#extend-text').val('');
  $('#extend-msg-succuss,#extend-msg-error').hide();
  $('#button-extend')[0].className = "pro-button01 button-style-disabled-1 button-go-extend-checkout-disabled";
  $('#popup-extend').show();
};
//购买延保订单
ec.product.extendBuy = function (obj) {
  //BI上报
  _paq.push(['trackLink', '延保商品 - 提交订单', 'link', ' ']);
  ec.code.addAnalytics({
    hicloud: true
  });

  var imei = $.trim($('#extend-text').val());
  if (obj.className != 'pro-button01 button-style-1 button-go-extend-checkout' || !imei) return;

  ec.account.afterLogin(function () {

    var id = ec.product.getSku(),
      input = "",
      form = gid("order-confirm-extend-form");

    if (!ec.util.isArray(id)) {
      id = [id];
    }
    for (var i = 0; i < id.length; i++) {
      input += '<input name="skuIds" type="text" value="' + id[i] + '">';
    }
    input += '<input name="imei" type="text" value="' + imei + '">';
    form.innerHTML = input;
    //判断用户是否绑定手机或者华为邮箱
    ec.binding.isBindedMobileOrEnterpriseUser(function () {
      setTimeout(function () {
        form.submit();
      }, 500);
    });
  });
};




//合约机
ec.product.initContract = function (sku) {
  // 合约机
  if (sku.contractList.length > 0) {
    // 合约机
    var lst, _contractListObj;
    //
    //		<li class="attr2 selected" data-attrname="颜色" data-attrid="2" data-skuid="398165679"><div class="sku"><a href="javascript:;" title="流光金">
    //		<img src="https://cdnkf.vmall.com/edp-deploy/pimages/product/mate900001/40_40_1493195152599mp.jpg" alt="流光金"><p><span>流光金</span></p></a></div></li>
    html = [];
    for (var i = 0; i < sku.contractList.length; i += 1) {
      lst = sku.contractList[i];
      html.push('<li data-id="' + lst.id + '"> <div class="sku"><a title="' + lst.name + '" href="javascript:;"><p><span>' + lst.name + '</span></p></a><s></s></div ></li>');

    }
    _contractListObj = $(html.join(""));

    $('.sku', _contractListObj).click(function () {
      $(this).parent().toggleClass('selected').siblings().removeClass('selected');
    });

    $('#contractList-ol').html(_contractListObj);
    $('#contractLst').show();

    $("#contractLst .sku").unbind("click").click(function () {
      $(this).parent().toggleClass('selected').siblings().removeClass('selected');

      var $quantityObj = $('#pro-quantity-area'),
        $liSelected = $("#contractLst li.selected"),
        $btn = $('#pro-operation'),
        $contractForm = $('#contractForm'),
        _sku, _haveInventory;


      ec.product.addCartBtn = ec.product.addCartBtn || $btn.html();
      _sku = ec.product.getSku();
      _haveInventory = ec.product.inventory.haveInventory(_sku);
      if (ec.product.status == 3) {
        ec.product.execute("renderInventory", [_haveInventory]);
        //$btn.html(ec.product.addCartBtn).css('visibility', 'hidden');
        $quantityObj.show();
      } else {
        if ($liSelected.length > 0 && _haveInventory) {
          $quantityObj.hide();
          $btn.html($('<a class="product-button02" href="javascript:;"><span>立即购买</span></a>').click(function () {
            //BI统计
            _paq.push(['trackLink', '合约机-立即购买', 'link', ' ']);
            ec.code.addAnalytics({
              hicloud: true
            });

            var finalGift = ec.product.gift.finalMainSbomGiftMap[ec.product.getSku()];
            var gifts = [];
            if (finalGift) {
              for (var key in finalGift) {
                gifts.push(finalGift[key].giftSkuCode);
              }
            }
            var form = gid("contractForm");
            form.innerHTML = '<input name="gifts" type="text" value="' + gifts + '">';

            setTimeout(function () {
              var url = $contractForm.attr('action');
              $contractForm.attr('action', url.replace('{id}', $liSelected.attr('data-id'))).submit();
            }, 200);

          })).css('visibility', 'visible');
          $("#product-operation").show(); //console.log("product-operation.show()");
        } else if ($liSelected.length > 0 && !_haveInventory) {
          var $buyBtnMod = $("#pro-operation");
          $("#pro-quantity-area").hide();
          $buyBtnMod.css("visibility", "visible");
          $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.arrival()"><span>到货通知</span></a>');
          $("#tab-notice-button").show();
          $("#product-operation").show(); //console.log("product-operation.show()");

          $quantityObj.show();
        } else {
          ec.product.execute("renderInventory", [_haveInventory]);
          //$btn.html(ec.product.addCartBtn).css('visibility', 'hidden');
          $quantityObj.show();
        }
      }
    });
    //默认选中第一个
    $("#contractLst .sku").eq(0).click();
  } else {
    $('#contractLst').hide();
  }
};
//跳转到评论tab
ec.product.jmptoRemark = function () {
  $('#pro-tab-evaluate').click();
  ec.ui.scrollTo("#pro-tab-evaluate");
};

//增加处理checkbox样式的代码，对隐藏的checkbox表单操作，并计算当前选择的套餐价格
ec.product.combClick = function (ths) {
  if ($(ths).hasClass("selected") == false) {
    $(ths).addClass("selected");
    $(ths).children("input").attr("checked", true);
  } else {
    $(ths).removeClass("selected");
    $(ths).children("input").attr("checked", false);
  }
  var thix = $(ths).children("input");
  count = parseInt($("#comb-count").html(), 10) || 0,
    price = parseFloat($("#comb-price").html()) || 0;

  if (thix.attr("checked") == true) {
    price += parseFloat(thix.attr("data-price"));
    count++;
  } else {
    price -= parseFloat(thix.attr("data-price"));
    count--;
  }

  //当商品类型不是订金商品的时候才更新组合价，更新组合价交给ec.product.depositActivity
  if (!(ec.product.productType && ec.product.productType == 4 && ec.product.isDespositSku == 1)) {
    $("#comb-price").html(price.toFixed(2));
  }

  $("#comb-count").html(count);
};

(function () {
  var _index = 0,
    _length;

  ec.ready(function () {
    _length = $("#pro-gallerys").css("left", "0").children().length;
  });

  ec.product.imgSlider = {
    prev: function () {
      if (_index == 0) return;
      _index--;
      $("#pro-gallerys").animate({
        "left": _index * -62
      }, 100);
    },
    next: function () {
      if (_index + 5 >= _length) return;
      _index++;

      $("#pro-gallerys").animate({
        "left": _index * -62
      }, 100);
    },
    reset: function () {
      _length = $("#pro-gallerys").css("left", "0").children().length;
      _index = 0;
    }
  };
})();

(function (_ep) {

  var _bundleId,
    _renderComb = function (skuId) {
      var comb = $("#comb-pro-" + skuId);


      //计算价格
      var sku = _ep.getSkuInfo(skuId),
        //price = sku.skuPrice; //优惠价
        price = parseFloat(sku.price);

      comb.find("input[name=skuId]:checked").each(function () {
        price += parseFloat(this.getAttribute("data-price"));
      });

      //当商品类型不是订金商品的时候才更新组合价，更新组合价交给ec.product.depositActivity
      if (!(ec.product.productType && ec.product.productType == 4 && ec.product.isDespositSku == 1)) {
        $("#comb-price").html(price.toFixed(2));
      }
    };

  //渲染页面的组合套装和捆绑
  _ep.renderGroup = function (skuId) {

    var _showId = [],

      bundle = $("#bundle-list-" + skuId),
      comb = $("#comb-pro-" + skuId);

    //该sku有套装
    if (bundle.length > 0) {
      _showId.push("#tab-bundle");
      bundle.show().siblings().hide();
      _ep.renderBundle(skuId);
    }

    //该sku有推荐商品
    if (comb.length > 0) {
      _showId.push("#tab-comb");
      $("#comb-" + skuId).show().siblings().hide();
      comb.show().siblings().hide();
      _renderComb(skuId);
    }

    $("#tab-bundle,#tab-comb").hide();
    if (_showId.length == 0) {
      $("#group-area").hide();
      return;
    }

    if (_showId.length > 1) {
      _showId.push("#tab-split");
    }

    _showId.push("#group-area");
    $(_showId.join(",")).show();

  };

  _ep.renderBundle = function (skuId) {
    var bundleList = $("#bundle-list-" + skuId);
    this.showBundle(bundleList.children("li.current").attr("data-id"));
  };

  _ep.showBundle = function (bundleId) {
    $("#bundle-pro-" + bundleId + ",#bundle-price-" + bundleId).show().siblings().hide();
    _bundleId = bundleId;

    var bundle = $("#bundle-pro-" + bundleId);
  };


})(ec.product);


//配置
(function () {

  var _type;
  _options = {};
  _options["default"] = {};

  _options["normal"] = {
    //渲染操作区
    renderInventory: function (haveQuantity) {
      var getSku = ec.product.getSkuInfo(ec.product.getSku() || ec.product.defaultSku),
        $proMsg = $("#pro-msg"),
        $buyBtns = $("#pro-quantity-area,#pro-operation"),
        $buyBtnMod = $("#pro-operation"),
        isPriority = $("#isPriority").val();;


      $("#tab-addcart-button").hide();
      $("#tab-notice-button").hide();

      $("#product-tips").html("");
      $("#product-tips").hide();

      if (ec.product.status == 3) { //下架商品
        $proMsg.show();
        $("#pro-msg-title").html("温馨提示：该商品已下架");
        $buyBtnMod.css("visibility", "hidden");

        $("#pro-skus").html("");
        $("#pro-skus").hide();
        $('.product-operation-main').hide();

        return;
      }

      if (ec.product.status == 5) { //该商品不在此销售前端销售
        $proMsg.show();
        $("#pro-msg-title").html("温馨提示：该商品不在此销售前端销售");
        $buyBtnMod.css("visibility", "hidden");

        $("#product-tips").html("温馨提示：该商品不在此销售前端销售");
        $("#product-tips").show();
        $("#product-operation").hide();

        return;
      }

      //提示内容, 有则显示，无则隐藏
      if (getSku.tipsContent.length > 1) {
        $proMsg.show();
        $("#pro-msg-title").html("温馨提示：" + getSku.tipsContent);

        $("#product-tips").html("温馨提示：" + getSku.tipsContent);
        $("#product-tips").show();
        //$("#product-operation").hide();

      } else {
        $proMsg.hide();
        $("#product-tips").hide();
      }

      //价格显示方式，1：正常显示；2：暂不报价
      if (getSku.priceMode == 2) {
        $("#pro-price-label").html('暂无报价');
        $("#pro-price-label").show();
        $("#pro-price").hide();
        $("#pro-price-old").hide();
        $("#pro-price").html('');
        $("#pro-price-old").hide();
      }

      if (isPriority == 1) {
        if (ec.product.getSkuPriority(getSku.id) == true) {
          $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.buy('
            sku ');return false;"><span>立即购买</span></a>');
          $("#pro-quantity-area").hide();
          $buyBtnMod.css("visibility", "visible");
          $("#product-operation").show(); //console.log("product-operation.show()");
          $("#order-confirm-form").attr({
            "action": "/order/priorityConfirm",
            "method": "post"
          });
          return;
        }
      }

      $("#order-confirm-form").attr({
        "action": "/order/nowConfirmcart",
        "method": "post"
      });

      /*
      	按钮显示方式

      	1：正常加入购物车；
      	2：DBank下单(立即购买)；
      	3：新品下单(预留,暂时没用)；
      	4：关注商品；
      	5：无按钮;
      	6:延保商品(立即购买)
      */
      //console.log("buttonMode:"+getSku.buttonMode);
      switch (parseInt(getSku.buttonMode, 10)) {
        case 5:
          $buyBtnMod.css("visibility", "hidden");
          $("#pro-quantity-area").hide();
          return;
        case 4:
          $buyBtnMod.css("visibility", "hidden");
          $("#pro-quantity-area").hide();
          return;
        case 2:
          $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.buy('
            sku ');return false;"><span>立即购买</span></a>');
          $("#pro-quantity-area").show();
          $buyBtnMod.css("visibility", "visible");
          $("#product-operation").show(); //console.log("product-operation.show()");
          return;
        case 6:
          $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.extendBuyNow();return false;"><span>立即购买</span></a>');
          $("#pro-quantity-area").show();
          $buyBtnMod.css("visibility", "visible");
          $("#product-operation").show(); //console.log("product-operation.show()");
          return;
        case 7:
          if (ec.product.isEasyBuy()) {
            $("#pro-quantity-area").hide();
            $("#pro-quantity-area-nochange").show();
            $buyBtnMod.html('<a onclick="ec.product.orderEasyBuy()" class="product-button01" ><span>优享购</span></a>' +
              '<a target="_blank" href="' + getSku.gotoUrl + '" class="product-button02" ><span>立即预约</span></a>');
          } else {
            $buyBtnMod.html('<a target="_blank" href="' + getSku.gotoUrl + '" class="product-button02" ><span>立即预约</span></a>');
          }
          $buyBtnMod.css("visibility", "visible");
          $("#product-operation").show(); //console.log("product-operation.show()");
          return;
        case 8:
          //以new_detail.layout.ftl，pro-tab-parameter中的属性data-skulist-rushbuy
          //此方法会被执行两次，所以抢购处理逻辑入口改到其他地方
          //$buyBtnMod.html('<a target="_blank" href="'+getSku.gotoUrl+'" class="pro-button01 button-style-2 button-buy-start" title="参加抢购"><span>参加抢购</span></a>');
          //$buyBtnMod.css("visibility" , "visible");
          return;
        case 9:
          //9	-	开售提醒	【开售提醒】
          if (ec.product.isEasyBuy()) {
            $("#pro-quantity-area").hide();
            $("#pro-quantity-area-nochange").show();
            $buyBtnMod.html('<a onclick="ec.product.orderEasyBuy()" class="product-button01" ><span>优享购</span></a>' +
              '<a target="_blank" href="' + getSku.gotoUrl + '" class="product-button02" ><span>开售提醒</span></a>');
          } else {
            $buyBtnMod.html('<a target="_blank" href="' + getSku.gotoUrl + '" class="product-button02" ><span>开售提醒</span></a>');
          }
          $buyBtnMod.css("visibility", "visible");
          $("#product-operation").show(); //console.log("product-operation.show()");
          return;
        case 10:
          ec.product.timingBuy();
          return;
        case 11:
          //手机后壳定制业务cover
          if (haveQuantity) {
            $("#pro-quantity-area").show();
            $buyBtnMod.css("visibility", "visible");
            $("#product-operation").show(); //console.log("product-operation.show()");

            var html = '<a href="javascript:;" onclick="ec.product.orderNowCover()" class="product-button02" ><span>立即下单</span></a>';
            $buyBtnMod.html(html);
            //							$("#tab-addcart-button").show();

          } else {
            //$proMsg.hide();
            $("#pro-quantity-area").hide();
            $buyBtnMod.css("visibility", "visible");
            $("#product-operation").show(); //console.log("product-operation.show()");

            $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.arrival()"><span>到货通知</span></a>');
            $("#tab-notice-button").show();

          }

          return;
        case 12:
          $buyBtnMod.css("visibility", "hidden");
          $("#pro-quantity-area").hide();
          return;
        default:
          if (haveQuantity) { //是否有库存
            $("#pro-quantity-area").show();
            $buyBtnMod.css("visibility", "visible");
            $("#product-operation").show(); //console.log("product-operation.show()");
            //$proMsg.hide();
            if (getSku.groupType == '1') {
              $buyBtnMod.html('<a href="javascript:;" onclick="ec.product.addCart()" class="product-button02" ><span>立即团购</span></a>');
            } else {
              var html = '<a href="javascript:;" onclick="ec.product.addCart()" class="product-button01" ><span>加入购物车</span></a>' +
                '<a href="javascript:;" onclick="ec.product.orderNow()" class="product-button02" ><span>立即下单</span></a>';
              $buyBtnMod.html(html);
              $("#tab-addcart-button").show();
            }
          } else {
            //$proMsg.hide();
            $("#pro-quantity-area").hide();
            $buyBtnMod.css("visibility", "visible");
            $("#product-operation").show(); //console.log("product-operation.show()");

            //普通购买-无库存	【到货通知】
            if (ec.product.isEasyBuy()) {
              $("#pro-quantity-area").hide();
              $("#pro-quantity-area-nochange").show();
              $buyBtnMod.html('<a onclick="ec.product.orderEasyBuy()" class="product-button02" ><span>优享购</span></a>');
            } else {
              $buyBtnMod.html('<a href="javascript:;" class="product-button02" onclick="ec.product.arrival()"><span>到货通知</span></a>');
              $("#tab-notice-button").show();
            }
          }

      }

    }
  };

  //实物预约购买
  _options["reservation"] = {
    renderInventory: function (haveQuantity) {

      $("#pro-msg").hide();
      if (haveQuantity) {
        $("#pro-quantity-area").show();
        $("#pro-operation").html('<a href="javascript:;"  onclick="ec.product.addCartWithLogin()" class="product-button02" ><span>预约购买</span></a>');

        $("#product-operation").show(); //console.log("product-operation.show()");

      } else {
        $("#pro-quantity-area").hide();
        //$("#pro-operation").html('<a href="javascript:;" class="button-sellOut" title="卖光了"><span>卖光了</span></a>');
        $("#pro-operation").html('<a href="javascript:;" class="product-button02" onclick="ec.product.arrival()"><span>到货通知</span></a>');

        $("#product-operation").show(); //console.log("product-operation.show()");

      }
    }
  };

  _options["queue"] = {
    renderInventory: function (haveQuantity) {
      if (haveQuantity) {
        $("#sale-buy-btn").show();
        $("#sale-sell-out").hide();
      } else {
        $("#sale-buy-btn").hide();
        $("#sale-sell-out").show();
      }
    }
  };

  _options["seckill"] = {
    renderInventory: function (haveQuantity) {
      if (haveQuantity) {
        $("#sale-buy-btn").show();
        $("#sale-sell-out").hide();
      } else {
        $("#sale-buy-btn").hide();
        $("#sale-sell-out").show();
      }
    }
  };

  ec.product.execute = function (command, args) {
    var opt = _options[_type],
      fun = opt[command] || _options["default"][command];

    if (fun) fun.apply(ec.product, args);
  };

  ec.product.setType = function (type) {
    _type = type;
    switch (type) {
      case "normal":
      case "reservation":
        ec.product.isSale = false;
        break;
      default:
        ec.product.isSale = true;
    }
    //是否促销
    ec.product.prefix = ec.product.isSale ? "/sale" : "/product";
    //$.extend(ec.product , _options[type]);
  };
})();

ec.ready(function () {
  //左部图片相对右边居中效果--start
  $(function () {
    var fix = $('.product-gallery');
    var end = $('.gallery-scroll-bottom');
    var fixTop = fix.offset().top,
      fixHeight = fix.height();
    var endTop, miss;
    $(window).scroll(function () {
      var docTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
      if (end.length > 0) {
        endTop = $('.header').height() + (($('.hr-10').height()) * 4) + $('.g').height() + $('.product').height();
        miss = endTop - docTop - fixHeight;
      }
      if (fixTop < docTop) {
        fix.addClass('positionFixed');
        fix.removeClass('positionStatic');
        if ((end.length > 0) && (endTop < (docTop + fixHeight))) {
          fix.css({
            top: miss
          });
        } else {
          fix.css({
            top: 0
          });
        }
      } else {
        fix.addClass('positionStatic');
        fix.removeClass('positionFixed');
      }
    })
  });

  //	(function($){
  //	     function btnPosition() {
  //	        var rightHeight=$('#product-property-recommand').height()-$('#pro-predict').height();
  //	        if(rightHeight<=526){
  //	           $('.product-operation-main').addClass('product-operation-location');
  //	        }else{
  //	           $('.product-operation-main').removeClass('product-operation-location');
  //	        }
  //	    };
  //	    btnPosition();
  //	})(jQuery);
  //左部图片相对右边居中效果--end
  var product = ec.product;

  ec.ui.proNumer("#pro-quantity", {
    max: 999,
    min: 1
  });

  var loadEvaluate = false;
  var bFirstLoadEvaluate = false;

  //用户评价列表
  var _loadEvaluate = function (page) {
    new ec.ajax()
      .get({
        // url : ec.product.prefix +
        // "/queryEvaluate.json?pid="+ec.product.id+"&pageNumber=" +
        // page.pageNumber+rquest,
        url: ec.remark.prefix + "/queryEvaluate.json?pid=" + ec.product.id + "&pageNumber=" + page.pageNumber +
          "&t=" + new Date().getTime(),
        dataType: "jsonp",
        successFunction: function (json) {
          if (!json.success) {
            commentFlag = true;
            $("#pro-tab-evaluate-content").hide();
            $("#productCommentId").hide();
            $("#pro-tab-evaluate").hide();
            return;
          }
          if (json.remarkList.length == 0) {
            commentFlag = true;
            $("#pro-tab-evaluate-content").hide();
            $("#productCommentId").hide();
            $("#pro-tab-evaluate").hide();
            return;
          }
          commentFlag = false;
          $("#pro-tab-evaluate-content").show();
          $("#productCommentId").show();
          $("#pro-tab-evaluate").show();

          loadEvaluate = true;
          var html = [],
            p, v;

          for (var i = 0; i < json.remarkList.length; i++) {
            p = json.remarkList[i];

            html
              .push('<li class="clearfix"><div class="product-comment-user"><p class="product-comment-user-img">');
            var userPng = "/images/echannel/misc/defaultface_user_small.png";
            try {
              userPng = imagePath + "/echannel/misc/defaultface_user_small.png";
            } catch (err) {}
            html.push('<img src="' + userPng + '" alt="' + userPng + '">');
            var grade = p.gradeCode == null ? 0 : p.gradeCode;
            html.push('<i class="icon-vip-level-' + grade + '"></i></p>');
            html.push('<p class="product-comment-user-name">' + ec.util.escapeHtml(p.custName) +
              '</p></div>');
            html
              .push('<div class="product-user-comment"><div class="product-user-comment-detial"><div class="h clearfix">');
            html
              .push('<div class="product-star"><span class="starRating-area"><s style="width:' + (p.score * 20) + '%"></s></span>');
            html.push('</div><div class="product-user-comment-impress">');
            // 评价印象
            html.push('<dl>');
            for (var j = 0; j < p.labelList.length; j++) {
              html.push('<dd>' + ec.util.escapeHtml(p.labelList[j]) + '</dd>');
            }
            html.push('</dl></div></div>');
            // 评价内容
            html.push('<div>');
            html.push((ec.util.escapeHtml(p.content) || ""));
            html.push('</div>');
            // 评价时间
            html.push('<div class="product-user-comment-time">');
            html.push(p.createDate);
            html.push('</div></div>');

            for (var j = 0; j < p.msgReplyList.length; j++) {
              v = p.msgReplyList[j];
              html.push('<div class="product-admin-reply"><dl class="clearfix">');
              html.push('<dt>' + (ec.util.escapeHtml(v.replyerName) || "") + '回复：</dt>');
              html.push('<dd>' + (ec.util.escapeHtml(v.replyContent) || "") + '</dd>');
              html.push('</dl>');
              html.push('</div>');
            }
            html.push('</div></li>');

          }

          // 无评论的时候隐藏掉外面的虚线框
          var proMsgList = $("#pro-msg-list");
          proMsgList.html(html.join(""));
          if (json.remarkList.length == 0) {
            proMsgList.hide();
          } else {
            proMsgList.show();
          }
          $("#evaluatePageNumber").html('共' + json.page.totalRow + '条评论');
          $("#pro-tab-evaluate span").html('(' + json.page.totalRow + ')');
          if (json.page.totalPage > 1) {
            $("#pro-msg-pager").show();
            $("#pro-msg-pager").pager({
              pageNumber: json.page.pageNumber,
              pageCount: json.page.totalPage,
              recordCount: json.page.totalRow,
              qpageSize: 10,
              text: {
                first: "|&lt;",
                pre: "&lt",
                next: "&gt;",
                last: "&gt;|"
              },
              item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
              callBack: _loadEvaluate
            });
          }

          $("#pro-msg-pager li.link").live('click', function () {
            $("html,body").animate({
              scrollTop: $("#pro-tab-evaluate-content").offset().top - $("#product-tab").height()
            }, 100);
          });
        },
        timeoutFunction: function () {
          commentFlag = true;
          $("#pro-tab-evaluate-content").hide();
          $("#productCommentId").hide();
          $("#pro-tab-evaluate").hide();
        },
        errorFunction: function () {
          commentFlag = true;
          $("#pro-tab-evaluate-content").hide();
          $("#productCommentId").hide();
          $("#pro-tab-evaluate").hide();
        }
      });
  };

  var _loadEvaluateScore = function () {
    new ec.ajax().get({
      url: ec.remark.prefix + "/queryEvaluateScore.json?pid=" + ec.product.id + "&t=" + new Date().getTime(),
      dataType: "jsonp",
      successFunction: function (json) {
        if (!json.success) {
          return;
        }

        // 显示评价数量 并计算总数
        for (var i = 0; i < 3; i++) {
          var p = json.remarkLevelList[i];
          if (p) {
            if (i == 0) {
              $("#pro-evaluate-avgSorce").html(p.percent + '<em>%</em>');
            }
          }
        }
        // 表头评论统计数据加载
        if (json.remarkLabelList) {
          var html0 = [];
          for (var i = 0; i < json.remarkLabelList.length; i++) {
            var p = json.remarkLabelList[i];
            if (p.times > 0) {
              var temp = '<li><a href="javascript:;"><em>' + p.labelName + '</em><span>' + p.times +
                '</span></a></li>';
              html0.push(temp);
            }
          }
          $("#pro-score-impress").html(html0.join(""));
        }
      }
    });
  };

  //显示当前sku相关信息
  ec.product.tabSkuInfo(ec.product.setSkuId || ec.product.defaultSku);
  //异步获取规格参数
  var loadParameter = false;
  // Add by 陈稳 at 2015/11/18 start


  var _loadEvaluateSorce = function () {
    //用户评价得分
    if (loadEvaluate)
      return;

    _loadEvaluateScore();
    //用户评价列表
    $("#pro-tab-evaluate-content").show();
    _loadEvaluate({
      pageNumber: 1,
      type: -1
    });
  };
  _loadEvaluateSorce();


  var product = ec.product;
  // 不在页面打开就执行，滚动到页面最后才调用
  //_loadEvaluateSorce();
  _bindEvent();

  //		ec.ui.proNumer("#pro-quantity", {
  //			max:999,
  //			min:1,
  //			minusBtn : '<a href="javascript:;" title="减"><span>-</span></a>',
  //			plusBtn : '<a href="javascript:;" title="加"><span>+</span></a>'
  //		});

  //延保、意外保鼠标悬停事件
  //		$("#extendProtected,#accidentProtected").hover(function(){
  //			$(this).addClass("hover");
  //		},function(){
  //			$(this).removeClass("hover");
  //		});

  //#pro-tab-software
  $("#pro-tab-feature , #pro-tab-parameter , #pro-tab-package-service , #pro-tab-evaluate").click(function () {
    var thix = $(this),
      id = this.id;
    switch (id) {
      case "pro-tab-feature":
        _paq.push(['trackLink', 'Click PC_product_detail', 'link', ' ']);
        ec.code.addAnalytics({
          hicloud: true
        });
        break;
      case "pro-tab-package-service":
        _paq.push(['trackLink', 'Click PC_product_package', 'link', ' ']);
        ec.code.addAnalytics({
          hicloud: true
        });
        break;
      case "pro-tab-parameter":
        _paq.push(['trackLink', 'Click PC_product_spec', 'link', ' ']);
        ec.code.addAnalytics({
          hicloud: true
        });
        break;
      case "pro-tab-evaluate":
        {
          _paq.push(['trackLink', 'Click PC_product_reviews', 'link', ' ']);
          ec.code.addAnalytics({
            hicloud: true
          });
          break;
        }
    }
  });

  ec.product.history.add(ec.product.id);

  $(window).scroll(function () {
    var hisScroll = $(this).scrollTop(),
      winHeight = $(window).height(),
      scrollTop = $('#product-history-area').offset().top;
    if (finished && hisScroll >= (scrollTop - winHeight)) {
      finished = false;
      //加载最近浏览历史
      product.history.load(function (list) {
        if (list.length == 0) {
          $("#product-history-area").hide();
          return;
        }

        var html = [],
          p;
        for (var i = 0; i < list.length; i++) {
          p = list[i];
          p.price = (p.priceMode == 2) ? '<em  class="disabled">暂无报价</em>' : '<em>&yen;' + p.price + '</em>';
          html.push('<li class="swiper-slide">');
          html.push('<a href="/product/' + p.id + '.html"  title="' + p.name + '"  onclick='
            _paq.push(["trackLink", "Click PC_historybrosing_product", "link", ""]); ec.code.addAnalytics({
              hicloud: true
            })
            ' target="_blank">');
          html.push('<img src="' + ec.mediaPath + p.photoPath + '142_142_' + p.photoName + '" alt="' + p.name + '"/>');
          html.push('<div class="product-link-detail">');
          html.push('<p><span>' + p.name + '</span></p>');
          html.push('' + p.price + '');
          html.push('</div>');
          html.push('</a>');
          html.push('</li>');
        }
        $("#product-history-list").html("");
        $("#product-history-list").html(html.join(" "));
        $("#product-history-area").show();
        ec.product.scroll("product-history-scroll", 5);
      }, null, ec.product.isSale ? null : ec.product.id);
    }
  })


  //显示默认的组合套餐
  product.renderGroup(product.setSkuId || product.defaultSku);

  var comb_timer;
  //优惠套装的tab
  $("#product-package-area li").mouseover(function () {
    var thix = $(this);
    thix.addClass("current").siblings().removeClass("current");
    product.showBundle(thix.attr("data-id"));
  });

  //显示默认的优惠套装
  product.renderBundle(product.setSkuId || product.defaultSku);

  //选中推荐配件
  $("#comb-pro-area input").click(function () {
    var thix = $(this),
      //ct = thix.parent().parent(),
      count = parseInt($("#comb-count").html(), 10) || 0,
      price = parseFloat($("#comb-price").html()) || 0;

    if (this.checked) {
      //ct.addClass("selected");
      price += parseFloat(thix.attr("data-price"));
      count++;
    } else {
      //ct.removeClass("selected");
      price -= parseFloat(thix.attr("data-price"));
      count--;
    }

    $("#comb-price").html(price.toFixed(2));
    $("#comb-count").html(count);
  });

  new ec.ajax().get({
    url: ec.remark.prefix + "/queryPrdinfoEvaluateScore.json?pid=" + ec.product.id + "&t=" + new Date().getTime(),
    dataType: "jsonp",
    successFunction: function (json) {
      $("#prd-remark-scoreAverage").attr("style", "width:" + (json.prdRemarkNum.scoreAverage * 20) + "%");
      $("#prd-remark-scoreAverage").show();

      $("#prd-remark-jmptoremark").attr("title", "共 " + json.prdRemarkNum.totalPrdCount + " 条评论");
      $("#prd-remark-jmptoremark").html("共&nbsp;" + json.prdRemarkNum.totalPrdCount + "&nbsp;条评论");
      $("#prd-remark-jmptoremark").show();

      $("#prd-remark-span-tab-evaluate").html("用户评价<em>（" + json.prdRemarkNum.totalPrdCount + "）</em>");
      $("#prd-remark-span-tab-evaluate").show();
    }
  });


  //合约机
  var sku = ec.product.getSku();
  sku = ec.product.getSkuInfo(sku);

  ec.product.initContract(sku);

  //延保
  ec.form.input.label('#extend-text', '输入IMEI/SN/MEID信息');

});

//全部咨询，常见问题，商品咨询，支付，配送，售后TAB切换
ec.product.divchange = function (data) {
  if (data == 1) {
    _paq.push(['trackLink', 'Click PC_all_inquiry', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").show();
    $("#prddetail_counsel_prd").hide();
    $("#prddetail_counsel_pay").hide();
    $("#prddetail_counsel_trans").hide();
    $("#prddetail_counsel_service").hide();
    $("#prddetail_counsel_ques").hide();
    $("#prd_detail_counsel_2").removeAttr('class');
    $("#prd_detail_counsel_3").removeAttr('class');
    $("#prd_detail_counsel_4").removeAttr('class');
    $("#prd_detail_counsel_5").removeAttr('class');
    $("#prd_detail_counsel_6").removeAttr('class');
    $("#prd_detail_counsel_1").attr('class', 'selected');
  } else if (data == 2) {
    _paq.push(['trackLink', 'Click PC_product_info', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").hide();
    $("#prddetail_counsel_prd").show();
    $("#prddetail_counsel_pay").hide();
    $("#prddetail_counsel_trans").hide();
    $("#prddetail_counsel_service").hide();
    $("#prddetail_counsel_ques").hide();
    $("#prd_detail_counsel_1").removeAttr('class');
    $("#prd_detail_counsel_3").removeAttr('class');
    $("#prd_detail_counsel_4").removeAttr('class');
    $("#prd_detail_counsel_5").removeAttr('class');
    $("#prd_detail_counsel_6").removeAttr('class');
    $("#prd_detail_counsel_2").attr('class', 'selected');
    ec.product.counselloadprd({
      "pageNumber": 1
    });
  } else if (data == 3) {
    _paq.push(['trackLink', 'Click PC_product_payment', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").hide();
    $("#prddetail_counsel_prd").hide();
    $("#prddetail_counsel_pay").show();
    $("#prddetail_counsel_trans").hide();
    $("#prddetail_counsel_service").hide();
    $("#prddetail_counsel_ques").hide();
    $("#prd_detail_counsel_1").removeAttr('class');
    $("#prd_detail_counsel_2").removeAttr('class');
    $("#prd_detail_counsel_4").removeAttr('class');
    $("#prd_detail_counsel_5").removeAttr('class');
    $("#prd_detail_counsel_6").removeAttr('class');
    $("#prd_detail_counsel_3").attr('class', 'selected');
    ec.product.paycounselload({
      "pageNumber": 1
    });
    // ec.product.paycounselload(page);
  } else if (data == 4) {
    _paq.push(['trackLink', 'Click PC_product_delivery', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").hide();
    $("#prddetail_counsel_prd").hide();
    $("#prddetail_counsel_pay").hide();
    $("#prddetail_counsel_trans").show();
    $("#prddetail_counsel_service").hide();
    $("#prddetail_counsel_ques").hide();
    $("#prd_detail_counsel_2").removeAttr('class');
    $("#prd_detail_counsel_3").removeAttr('class');
    $("#prd_detail_counsel_1").removeAttr('class');
    $("#prd_detail_counsel_5").removeAttr('class');
    $("#prd_detail_counsel_6").removeAttr('class');
    $("#prd_detail_counsel_4").attr('class', 'selected');
    ec.product.transcounselload({
      "pageNumber": 1
    });
    // ec.product.transcounselload(page);
  } else if (data == 5) {
    _paq.push(['trackLink', 'Click PC_product_afterservice', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").hide();
    $("#prddetail_counsel_prd").hide();
    $("#prddetail_counsel_pay").hide();
    $("#prddetail_counsel_trans").hide();
    $("#prddetail_counsel_service").show();
    $("#prddetail_counsel_ques").hide();
    $("#prd_detail_counsel_1").removeAttr('class');
    $("#prd_detail_counsel_3").removeAttr('class');
    $("#prd_detail_counsel_4").removeAttr('class');
    $("#prd_detail_counsel_2").removeAttr('class');
    $("#prd_detail_counsel_6").removeAttr('class');
    $("#prd_detail_counsel_5").attr('class', 'selected');
    ec.product.sercounselload({
      "pageNumber": 1
    });
    // ec.product.sercounselload(page);
  } else {
    _paq.push(['trackLink', 'Click PC_common_inquiry', 'link', ' ']);
    ec.code.addAnalytics({
      hicloud: true
    });
    $("#prddetail_counsel_all").hide();
    $("#prddetail_counsel_prd").hide();
    $("#prddetail_counsel_pay").hide();
    $("#prddetail_counsel_trans").hide();
    $("#prddetail_counsel_service").hide();
    $("#prddetail_counsel_ques").show();
    $("#prd_detail_counsel_1").removeAttr('class');
    $("#prd_detail_counsel_3").removeAttr('class');
    $("#prd_detail_counsel_4").removeAttr('class');
    $("#prd_detail_counsel_5").removeAttr('class');
    $("#prd_detail_counsel_2").removeAttr('class');
    $("#prd_detail_counsel_6").attr('class', 'selected');
    // ec.product.quescounselload({"pageNumber": 1});
    // ec.product.quescounselload(page);
  }
};

ec.product.counselloadall = function (page) {
  new ec.ajax()
    .submit({
      url: "/product/query/consultation/" + ec.product.id + ".json",
      data: {
        "prdId": ec.product.id,
        "dataType": 0,
        "pageNumber": page.pageNumber,
        "pageSize": 3
      },
      timeout: 10000,
      timeoutFunction: function () {
        alert("读取超时，请重试！");
      },
      successFunction: function (json) {
        if (!json.success) {
          ec.showError(json);
          return;
        }
        var html = [];
        html = ec.product.createcounselhtml(json);
        // 无评论的时候隐藏掉外面的虚线框

        $("#all_prd_counsel_content").html(html.join(""));


        ec.product.allrenderPage(json.page);
      }
    });
};
ec.product.allrenderPage = function (page) {
  $("#all_prd_counsel").show();
  $("#all_prd_counsel").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 3,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.counselloadall
  });
  ec.product.pagerScroll('all_prd_counsel');
};

ec.product.counselloadprd = function (page) {
  new ec.ajax().submit({
    url: "/product/query/consultation/" + ec.product.id + ".json",
    data: {
      "prdId": ec.product.id,
      "dataType": 1,
      "pageNumber": page.pageNumber,
      "pageSize": 3
    },
    timeout: 10000,
    timeoutFunction: function () {
      alert("读取超时，请重试！");
    },
    successFunction: function (json) {
      if (!json.success) {
        ec.showError(json);
        return;
      }
      var html = [];
      html = ec.product.createcounselhtml(json);
      // 无评论的时候隐藏掉外面的虚线框

      $("#prd_prd_counsel_content").html(html.join(""));
      if (json.page.totalRow > 0) {
        $("#prddetail_counsel_prd_total > div:first-child").html('共' + json.page.totalRow + '条');
      } else {
        $("#prddetail_counsel_prd_total").hide();
      }


      ec.product.prdrenderPage(json.page);
    }
  });
};

ec.product.prdrenderPage = function (page) {
  $("#prd_prd_counsel").show();
  $("#prd_prd_counsel").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 3,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.counselloadprd
  });
  ec.product.pagerScroll('prd_prd_counsel');
};

ec.product.paycounselload = function (page) {
  new ec.ajax().submit({
    url: "/product/query/consultation/" + ec.product.id + ".json",
    data: {
      "prdId": ec.product.id,
      "dataType": 2,
      "pageNumber": page.pageNumber,
      "pageSize": 3
    },
    timeout: 10000,
    timeoutFunction: function () {
      alert("读取超时，请重试！");
    },
    successFunction: function (json) {
      if (!json.success) {
        ec.showError(json);
        return;
      }
      var html = [];
      html = ec.product.createcounselhtml(json);
      // 无评论的时候隐藏掉外面的虚线框

      $("#pay_prd_counsel_content").html(html.join(""));
      if (json.page.totalRow > 0) {
        $("#prddetail_counsel_pay_total > div:first-child").html('共' + json.page.totalRow + '条');
      } else {
        $("#prddetail_counsel_pay_total").hide();
      }


      ec.product.payrenderPage(json.page);
    }
  });
};

ec.product.payrenderPage = function (page) {
  $("#pay_prd_counsel_page").show();
  $("#pay_prd_counsel_page").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 3,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.paycounselload
  });
  ec.product.pagerScroll('pay_prd_counsel_page');
};

ec.product.transcounselload = function (page) {
  new ec.ajax().submit({
    url: "/product/query/consultation/" + ec.product.id + ".json",
    data: {
      "prdId": ec.product.id,
      "dataType": 3,
      "pageNumber": page.pageNumber,
      "pageSize": 3
    },
    timeout: 10000,
    timeoutFunction: function () {
      alert("读取超时，请重试！");
    },
    successFunction: function (json) {
      if (!json.success) {
        ec.showError(json);
        return;
      }
      var html = [];
      html = ec.product.createcounselhtml(json);
      // 无评论的时候隐藏掉外面的虚线框

      $("#trans_prd_counsel_content").html(html.join(""));
      if (json.page.totalRow > 0) {
        $("#prddetail_counsel_trans_total > div:first-child").html('共' + json.page.totalRow + '条');
      } else {
        $("#prddetail_counsel_trans_total").hide();
      }


      ec.product.transrenderPage(json.page);
    }
  });
};

ec.product.transrenderPage = function (page) {
  $("#trans_prd_counsel_page").show();
  $("#trans_prd_counsel_page").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 3,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.transcounselload
  });
  ec.product.pagerScroll('trans_prd_counsel_page');
};

ec.product.sercounselload = function (page) {
  new ec.ajax().submit({
    url: "/product/query/consultation/" + ec.product.id + ".json",
    data: {
      "prdId": ec.product.id,
      "dataType": 4,
      "pageNumber": page.pageNumber,
      "pageSize": 3
    },
    timeout: 10000,
    timeoutFunction: function () {
      alert("读取超时，请重试！");
    },
    successFunction: function (json) {
      if (!json.success) {
        ec.showError(json);
        return;
      }
      var html = [];
      html = ec.product.createcounselhtml(json);
      // 无评论的时候隐藏掉外面的虚线框

      $("#ser_prd_counsel_content").html(html.join(""));
      if (json.page.totalRow > 0) {
        $("#prddetail_counsel_serv_total > div:first-child").html('共' + json.page.totalRow + '条');
      } else {
        $("#prddetail_counsel_serv_total").hide();
      }


      ec.product.serrenderPage(json.page);
    }
  });
};

ec.product.serrenderPage = function (page) {
  $("#ser_prd_counsel_page").show();
  $("#ser_prd_counsel_page").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 3,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.sercounselload
  });
  ec.product.pagerScroll('ser_prd_counsel_page');
};

ec.product.quescounselload = function (page) {
  new ec.ajax()
    .submit({
      url: "/product/query/frequentyQuestions/" + ec.product.id + ".json",
      data: {
        "prdId": ec.product.id,
        "pageNumber": page.pageNumber,
        "pageSize": 10
      },
      timeout: 10000,
      timeoutFunction: function () {
        alert("读取超时，请重试！");
      },
      successFunction: function (json) {
        if (!json.success) {
          ec.showError(json);
          return;
        }
        var html = [];
        if (json.page.totalRow > 0) {
          for (var i = 0; i < json.prdFrequentyQuestionsList.length; i++) {
            var p = json.prdFrequentyQuestionsList[i];
            html.push('<li>');
            html.push('<h2>' + ((page.pageNumber - 1) * 10 + i + 1) + '、' + p.question + '</h2>');
            html.push('<p>' + p.reply + '</p>');
            html.push('</li>');
          }
        } else {
          html.push('<div class="product-inquire-list"><div class="product-inquire-no">暂无相关内容</div></div>');
        }
        $("#ques_prd_counsel_content").html(html.join(""));

        if (json.page.totalRow > 0) {
          $("#prddetail_counsel_ques_total div:first-child").html('共' + json.page.totalRow + '条');
        } else {
          $("#prddetail_counsel_ques_total").hide();
        }


        ec.product.quesrenderPage(json.page);
      }
    });
};
ec.product.quesrenderPage = function (page) {
  $("#ques_prd_counsel_page").show();
  $("#ques_prd_counsel_page").pager({
    pageNumber: page.pageNumber,
    pageCount: page.totalPage,
    pageSize: 10,
    text: {
      first: "|&lt;",
      pre: "&lt",
      next: "&gt;",
      last: "&gt;|"
    },
    item: ["first", "pre", "qpage", "next", "last", "quickPager"], // 显示样式
    callBack: ec.product.quescounselload
  });
  ec.product.pagerScroll('ques_prd_counsel_page');
};
ec.product.createcounselhtml = function (json) {
  var html = [];
  if (json.page.totalRow > 0) {
    html.push('<ul class="product-inquire-list">');
    for (var i = 0; i < json.prdConsultationList.length; i++) {
      p = json.prdConsultationList[i];
      // var grade = p.gradeCode == null ? 0 : p.gradeCode;
      var username = p.userName;
      var gradecode = p.gradeCode;
      var date = new Date(p.createTime);
      var answerdate = new Date(p.answerTime);
      html.push('<li> <div class="product-inquire-user">网友'); // pro-comment-item
      // start

      // 用户信息
      html.push('<span>' + username + '</span>');
      html.push('<label>' + gradecode + '</label>');
      html.push('<em>' + date.format("yyyy-MM-dd HH:mm:ss") + '</em></div>');

      html.push('<div class="product-inquire-question">'); // pro-user-comment-main
      // start

      html.push('<label>咨询内容：</label><span>' + ec.util.escapeHtml(p.question) + '</span></div>');

      html.push('<div class="product-inquire-answer">');
      html.push('<p><label>回复：</label>' + ec.util.escapeHtml(p.answer) + '</p>');
      html.push('<em>' + answerdate.format("yyyy-MM-dd HH:mm:ss") + '</em>');
      html.push('</div></li>');
    }
    html.push('</ul>');
  } else {
    html.push('<div class="product-inquire-list"><div class="product-inquire-no">暂无相关内容</div></div>');
  }
  return html;
};
ec.product.loginCheckBefCoun = function () {
  if (!ec.account.isLogin()) {
    location.href = '/account/login?url=' +
      encodeURIComponent(window.location.pathname + '#counseltextid');
  } else {
    $("#counseltextid").focus();
    $("#error-span").hide();
  }
};
ec.product.submitCounsel = function () {
  var temptext = $("<div/>").text($("#counseltextid").val()).html();
  var text = ec.product.optCompany(temptext);
  if (text == null || text.length < 1) {
    $("#error-span").show();
    $("#error-span").html("提交内容为空");
    return;
  }
  if (text.length > 100) {
    $("#error-span").show();
    $("#error-span").html("输入的文字长度不能超过100个字,请重新输入");
    return;
  }

  new ec.ajax().get({
    url: domainMain + "/member/addUserRemarkView.json?t=" + new Date().getTime(),
    dataType: "json",
    data: {
      "orderCode": 'comments'
    },
    timeout: 10000,
    timeoutFunction: function () {
      alert("读取超时，请重试！");
      return false;
    },
    successFunction: function (json) {
      if (!json.success) {
        ec.account.syncCustomSession();
      }
      new ec.ajax().submit({
        url: "/product/save/consultation.json",
        form: "#counsel_content_form",
        data: {
          "productId": ec.product.id
        },
        successFunction: function (json) {
          if (!json.success) {
            if (json.msg == 'notRealName') {
              ec.product.commentsTip();
            } else {
              $("#error-span").show();
              $("#error-span").html(json.msg);
            }
          } else {
            if ($("#safeEmail").attr("checked")) {
              // 咨询成功
              ec.product.counselSuccess(json.changeEmailUrl);
            } else {
              alert("提交成功,请耐心等待客服人员的答复！");
            }

            $("#counsel_content_form")[0].reset();
            $("#error-span").hide();
            return;
          }
        }
      });
    }
  });
};

//评论弹框校验
ec.product.commentsTip = function () {
  new ec.box($('#realNameComment').val(), {
    boxclass: "ol_box_4",
    title: "",
    width: 540,
    showButton: false,
    autoHeight: false,
    onok: function () {}
  }).open();
};

/**
 * 去除左右空格
 */
ec.product.optCompany = function (str) {
  return str.replace(/(^s*)|(s*$)/g, "");
};

/**
 * 提交咨询成功后,弹出提示框
 */
ec.product.counselSuccess = function (url) {
  ec.account.afterLogin(function () {
    //更新用户信息
    ec.product.syncCustomSession();
    var email = ec.product.email;

    var box = new ec.box($("#product-counsel-html").val(), {
      boxid: "product-counsel-box",
      boxclass: "ol_box_4",
      showButton: false,
      onopen: function (box) {

        //判断用户是否已经绑定邮箱或手机号码
        if (ec.util.isEmpty(email)) {
          $("#counsel-success-msg").html('回复将发送到您的安全邮箱，您还未绑定，请先绑定安全邮箱。');
          $("#counsel-bind-email").html('<a href="' + url + '" class="box-change box-pro-button01 button-style-2" target="_blank" onclick="ec.product.secEmailOper()"><span>去绑定</span></a>');
        } else {
          $("#counsel-success-msg").html('客服回复将发送到您的安全邮箱&nbsp;' + email + '，可点击修改安全邮箱。');
          $("#counsel-bind-email").html('<a href="' + url + '" class="box-change box-pro-button01 button-style-2" target="_blank" onclick="ec.product.secEmailOper()"><span>修改安全邮箱</span></a>');
        }
      },
      onok: function (box) {},
      onclose: function (box) {
        $(".ol_box_mask").remove();
      }
    });
    box.open();

    //点击去绑定或者修改安全邮箱的同时，关闭到货通知对话框
    ec.product.secEmailOper = function () {
      box.close();
      $(".ol_box_mask").remove();
    };
  });
};




ec.product.combChange = function (data) {
  //获取选择的是 推荐配置几 模块
  var currentLi = $(data).parent();
  //将选择的推荐配置加上  当前   类型
  currentLi.addClass("current");
  //将除了当前选择的配置以外的所有其它推荐配置删除  选中 类型
  currentLi.siblings().not(currentLi).removeClass("current");
  //获取推荐配置的数据div的id
  var ulId = currentLi.parent().attr("id");
  //截取字符串，获取skuID
  var skuId = ulId.substring(14, ulId.length);
  //获取选取的推荐配置几
  var index = currentLi.index();
  //显示推荐配置的具体数据div模块

  var cuttentDivs = $('[id="comb-pro-' + skuId + '"]');

  var cuttentDiv = cuttentDivs.eq(index);
  cuttentDiv.show();
  cuttentDiv.siblings().not(cuttentDiv).hide();
};

//同步UP信息，更新session
ec.product.syncCustomSession = function () {
  new ec.ajax().get({
    async: false, //使用同步的Ajax请求
    url: "/account/syncEmailAndMobile.json",
    timeout: 10000,
    successFunction: function (json) {
      if (!ec.util.isEmpty(json.customerInfo)) {
        ec.product.email = json.customerInfo.email;
        ec.product.mobile = json.customerInfo.mobile;
      }
      return;
    },
    timeoutFunction: function () {
      return;
    },
    errorFunction: function () {
      return;
    }
  });
};

//查询系统时间
ec.product.getSysDate = function () {
  var now = new Date();
  new ec.ajax().get({
    async: false, //使用同步的Ajax请求
    url: "/system/getSysDate.json",
    timeout: 10000,
    successFunction: function (json) {
      if (!ec.util.isEmpty(json.now)) {
        now.setTime(json.now.parseDate('yyyy-MM-dd HH:mm:ss'));
      }
    }
  });
  return now;
};


//分割手机号码（倒数每4位加两个空格）
ec.product.splitMobile = function (mobile) {
  var result = "";
  for (var i = 0; i < (mobile.length); i++) {

    if ((mobile.length - i) % 4 == 0) {
      result += '&nbsp;&nbsp;';
    }
    result += mobile.substring(i, i + 1);
  }
  return result;
};

/**
 * 包装与售后
 */
ec.product.getPackageAndService = function (skuId) {

  var packageContent = ec.product.packageList[skuId];
  var serviceContent = ec.product.warranty[skuId];
  var hasPackage = packageContent ? true : false;
  var hasService = serviceContent ? true : false;
  var hasBoth = hasPackage && hasService;

  packFlag = !hasPackage && !hasService;

  //if(console && console.log){
  //	console.log(""+skuId+","+hasPackage+","+hasService+","+packFlag);
  //}

  $("#pro-tab-package-service-content").empty();
  $("#pro-tab-service-content").empty();
  $("#pro-tab-package-service-content").hide();
  $("#packagTitleId").hide();
  $("#customerServiceTitle").hide();
  $("#customerServiceDiv").hide();
  $("#pro-tab-package-service").hide();

  if (hasPackage) {
    $("#pro-tab-package-service-content").html(packageContent);
    $("#pro-tab-package-service-content").show();
    $("#packagTitleId").show();
    $("#pro-tab-package-service").show();
  }
  if (hasService) {
    $("#pro-tab-service-content").html(serviceContent);
    $("#customerServiceTitle").show();
    $("#customerServiceDiv").show();
    $("#pro-tab-package-service").show();
  }
}


ec.product.getFeature = function (skuId) {
  if (ec.product.getSkuForFeature(skuId) != undefined) {
    $("#pro-tab-parameter").removeClass("selected");
    $("#pro-tab-feature").addClass("selected").show();
    $("#pro-detail-contents").show();
    $('#pro-detail-content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
    return;
  }
  // 请求商品详情
  new ec.ajax().get({
    url: "/product/querySkuDetailFeature.json",
    data: {
      skuId: ec.product.getSku()
    },
    timeout: 10000,
    timeoutFunction: function () {
      $("#pro-detail-contents > div:first-child").html("正在加载...");
    },
    successFunction: function (json) {
      if (!json.success) {
        $("#pro-tab-feature").removeClass("selected").hide();
        $("#pro-tab-parameter").addClass("selected");
        $("#pro-detail-contents").hide();
        return;
      }
      if (json.length == 0) {
        $("#pro-tab-feature").removeClass("selected").hide();
        $("#pro-tab-parameter").addClass("selected");
        $("#pro-tab-feature").hide();
        $("#pro-detail-contents").hide();
        return;
      }
      $("#pro-tab-parameter").removeClass("selected");
      $("#pro-tab-feature").addClass("selected");
      $("#pro-tab-feature").show();
      $("#pro-detail-contents").show();
      ec.product.setSkuForFeature(skuId);
      var content = [];
      content.push('<div id="pro-detail-content-' + json.id + '" class="pro-detail-see">');

      content.push('<div id="kindPicture-' + json.id + '">');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      //			content.push('<p><img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/></p>');
      content.push(json.detail);
      content.push('</div>');
      //			content.push('<img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/>');
      //			content.push('<img src="https://res.vmallres.com/pimages//sale/2017-05/20170525221141240.jpg"/>');


      content.push('<div id="detail-content-button-' + json.id + '" class="product-shade hide"><p>');
      content.push('<a id="pro-detail-down-btn-' + json.id + '" class="product-detail-btn" onclick="_paq.push(["trackLink","Click PC_all_product_detail", "link", " "]);ec.code.addAnalytics({hicloud:true});">');
      content.push('查看全部产品详情</a></p></div>');
      content.push('<a href="javascript:;" id="pro-detail-up-btn-' + json.id + '" class="product-detail-btnup hide">收起全部产品详情</a>');
      content.push('</div>');
      var feature = $("#pro-tab-feature-content > div:first-child");
      feature.prepend(content.join(''));

      $('#pro-detail-content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
      var imgHeight = 0;
      $('#pro-detail-content-' + (ec.product.setSkuId || skuId) + ' img').each(function (index) {
        $(this).load(function () {
          imgHeight = imgHeight + $(this).height();
          if (imgHeight >= 2000) {
            $('#pro-detail-content-' + json.id).height('2000');
            $('#detail-content-button-' + json.id).show();
            $("#pro-detail-down-btn-" + json.id).click(function () {
              $('#pro-detail-content-' + json.id).height($('#kindPicture-' + json.id).height() + $('#pro-detail-up-btn-' + json.id).height() + 40);
              $('#detail-content-button-' + json.id).hide();
              $("#pro-detail-up-btn-" + json.id).css("display", "block");
              upDownButton = "true";
            });

            $("#pro-detail-up-btn-" + json.id).click(function () {
              $('#pro-detail-content-' + json.id).height('2000');
              $('#detail-content-button-' + json.id).show();
              $("#pro-detail-up-btn-" + json.id).css("display", "none");
              upDownButton = "false";
              $("body,html").animate({
                scrollTop: tit1 + 1575
              }, 0);
            });
            return false
          }
        });
      });
      if (imgHeight < 2000) {
        $('#detail-content-button-' + json.id).hide();
      }
    },
    errorFunction: function () {
      $("#pro-tab-feature").removeClass("selected").hide();
      $("#pro-tab-parameter").addClass("selected");
      $("#pro-detail-contents").hide();
    },
    timeoutFunction: function () {
      $("#pro-tab-feature").removeClass("selected").hide();
      $("#pro-tab-parameter").addClass("selected");
      $("#pro-detail-contents").hide();
    }
  });

};


//抢购业务逻辑入库函数，当sku设置默认或切换时调用
ec.product.rushbuyActivity = function () {
  //console.log("doIfSbomChanged");
  rush.business.doIfSbomChanged();
};

ec.product.switched = function (value, thix) {
  $("input[name='type']").val(value);
  $(thix).addClass("selected").siblings().removeClass("selected");
}
ec.product.getParameter = function (skuIds, skuCodes) {
  $("#parameterDetailTips").hide();
  if (ec.product.getSkuForParement(skuIds) != undefined) {
    //		 $('#parameter-content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
    $('#main-parameter-content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
    //$('#main-parameter-content-' + (ec.product.setSkuId || skuId)).show().siblings().remove();
    $('#content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
    $("#productParameterId").show();
    $("#productParameterHr30").show();
    return;
  }
  var skuList = skuIds.split(',');
  var skuCodeList = skuCodes.split(',');
  var reqParam = "";
  for (var i = 0; i < skuCodeList.length; i += 1) {
    reqParam += "sbomCode=" + skuCodeList[i];
    if (i < skuCodeList.length - 1) {
      reqParam += "&";
    }
  }

  $.ajax({
    url: pmsHttpDomain + "product/querySpecificationMulti.json?" + reqParam,
    dataType: "jsonp",
    jsonp: "callback", // 传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
    jsonpCallback: "flightHandler",
    timeout: 20000,
    success: function (json) {
      if (!json.success) {
        $("#parameterDetailTips").show();
        return;
      }
      $("#parameterDetailTips").hide();
      ec.product.setSkuForParement(skuIds);
      for (var n = 0; n < skuList.length; n += 1) {
        var skuId = skuList[n];
        var sbomCode = skuCodeList[n];
        var attrs = null;
        var mainAttrs = null;
        for (var m = 0; m < json.data.length; m += 1) {
          var specificationInfo = json.data[m];
          if (sbomCode == specificationInfo.sbomCode) {
            attrs = specificationInfo.specificationList;
            mainAttrs = specificationInfo.majorSpecificationList;
            break;
          }
        }
        var mainHtml = [];
        if (mainAttrs != null && mainAttrs.length > 0) {
          var mainP;
          mainHtml.push('<h2>主要参数</h2>');
          mainHtml.push('<ul>');
          for (var j = 0; j < mainAttrs.length; j++) {
            mainP = mainAttrs[j];
            if (mainP.value != null && mainP.value != "" && mainP.value != undefined) {
              mainHtml.push('<li><label>' + mainP.name + '</label><span>' + mainP.value + '</span></li>');
            }
          }
          mainHtml.push('</ul>');
        }
        $("#product-parameter-main").append(
          '<div id="main-parameter-content-' + skuId + '" class="product-parameter-main clearfix hide">' + mainHtml.join("") +
          '</div>');
        $('#main-parameter-content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
        //				$('#main-parameter-content-' + (ec.product.setSkuId || skuId)).show().siblings().remove();

        var html = [];
        if (attrs) {
          var p;
          var html0 = [];
          for (var i = 0; i < attrs.length; i++) {
            p = attrs[i];
            var html1 = [];
            if ("0" == p.parentCode) {
              html1.push('<div class="product-parameter-list clearfix">');
              html1.push('<h2>' + p.name + '</h2>');

              var code = p.code;
              var html2 = [];
              html2.push('<ul>');
              for (var j = 0; j < attrs.length; j++) {
                var p2 = attrs[j];
                if (p2.parentCode != "0" && p2.parentCode == code) {
                  html2.push('<li><label>' + p2.name + '</label><span>' + p2.value + '</span></li>');
                }
              }
              html2.push('</ul>');
              if (html2.length > 2) {
                html0.push(html1.join(""));
                html0.push(html2.join(""));
                html0.push('</div>');
              }
            }
          }
          html0.push('<div class="product-parameter-list clearfix">');
          html0.push('<h2>商品编码</h2>');
          html0.push('<ul><li><label>' + sbomCode + '</label><span></span></li></ul></div>');
          if (html0.length > 0) {
            //						html.push(html0.join(""));
            html.push('<div id="content-' + skuId + '" >');
            html.push('<div id="parameterContentButton-' + skuId + '" class="product-shade hide">');
            html.push('<p><a id="parameterDownButton-' + skuId + '"  href="javascript:;" onclick="_paq.push(["trackLink","Click PC_all_product_spec", "link", " "]);ec.code.addAnalytics({hicloud:true});"  class="product-detail-btn">查看全部参数</a></p>');
            html.push('</div>');
            html.push('<div id="pro-tab-parameter-content-' + skuId + '" class="layout">');
            html.push('<div id="parameter-content-' + skuId + '">');
            html.push(html0.join(""));
            html.push('</div>');
            html.push('</div>');
            html.push('<a id="parameterUpButton-' + skuId + '" href="javascript:;" class="product-detail-btnup hide">收起参数详情</a>');
            html.push('</div>');
          }
        }
        $("#productDetailParameter").prepend(html.join(""));
        $('#content-' + (ec.product.setSkuId || skuId)).show().siblings().hide();
        //				$("#pro-tab-parameter").show();
        //				if(html0.length == 0){
        //					$('#content-' + (ec.product.setSkuId || skuId)).hide();
        //					$("#pro-tab-parameter").hide();
        //					 $("#productParameterId").hide();
        //				}
      }
      $("#productParameterId").show();
      $("#productParameterHr30").show();
      var sku = ec.product.getSku();
      sku = ec.product.getSkuInfo(sku);
      var detailHeight = $('#parameter-content-' + sku.id).height();
      if (detailHeight <= 540 && detailHeight > 0) {
        $('#parameterContentButton-' + sku.id).removeClass("show").addClass("hide");
      } else {
        $('#parameterContentButton-' + sku.id).removeClass("hide").addClass("show");
        $('#pro-tab-parameter-content-' + sku.id).css({
          'height': '540',
          'overflow': 'hidden'
        });

        $("#parameterDownButton-" + sku.id).click(function () {
          $('#pro-tab-parameter-content-' + sku.id).height($('#parameter-content-' + sku.id).height());
          $("#parameterContentButton-" + sku.id).removeClass("show").addClass("hide");
          $("#parameterUpButton-" + sku.id).removeClass("hide").addClass("show");
        });

        $("#parameterUpButton-" + sku.id).click(function () {
          $("#parameterContentButton-" + sku.id).removeClass("hide").addClass("show");
          $("#parameterUpButton-" + sku.id).removeClass("show").addClass("hide");
          $('#pro-tab-parameter-content-' + sku.id).height('540');
          $("body,html").animate({
            scrollTop: tit1 + $('#pro-tab-feature-content').height() + $('#hr60Detail').height() + 270
          }, 0);
        });
      }

    },
    error: function () {
      $("#parameterDetailTips").show();
    }
  });
};
// Add by 陈稳 at 2015/11/18 end

function stopConsultation() {
  $("#stopConsultationId").hide();
  $("#myConsultation").show();
  $("#upUserAdvisory").removeClass("show").addClass("hide");
}

ec.product.switchSku = function () {
  oTop = $(".product-tab").offset().top;
  clickFlag = false;
  //	//console.log("==========切换点击detailContentHeight============="+detailContentHeight);
  //	tit2 = tit1 + detailContentHeight;
  //	tit3 = tit2 + productParameterHeight;
  //	tit4 = tit3 + packageServiceHeight + customerServiceHeight;
}

ec.product.pagerScroll = function (id) {
  $("#" + id + " li.link").click(function () {
    //分页定位到购买咨询
    $("html, body").animate({
      scrollTop: $("#productAsk").offset().top - $("#product-tab").height()
    });
  });

}

ec.product.videoShow = function () {
  $("#gallery-video-start").hide();
  $("#gallery-video-close").show();
  $("#video-container").show();
  $("#pic-container").hide();
  //window.tcplayer.togglePlay();
}

ec.product.videoHide = function () {
  $("#gallery-video-start").show();
  $("#gallery-video-close").hide();
  $("#video-container").hide();
  $("#pic-container").show();
  //window.tcplayer.togglePlay();
}

//	动态计算服务商品第一个li高度
ec.product.serverCommodity = function (id) {
  var num = $('#' + id + ' ul li').length,
    lineNum = Math.ceil((num - 1) / 2);
  liHeight = $('#' + id + ' ul li').height();
  $('#' + id + ' ul li').eq(0).css({
    'height': (lineNum * 24) - 6
  });
}
//左右切换滚动效果，num为滚动个数
ec.product.scroll = function (id, num) {
  var $div = $("#" + id).parent().parent();
  var len = $div.find('.swiper-slide').length;
  if (len <= num) {
    $div.find('.swiper-button-prev').addClass('disabled');
    $div.find('.swiper-button-next').addClass('disabled');
  } else {
    $div.find('.swiper-button-next').removeClass('disabled');
  }

  var mySwiper = new Swiper('#' + id, {
    slidesPerView: num,
    slidesPerGroup: num
  });
  //	左边箭头
  $div.find('.swiper-button-prev').click(function () {
    //		插件向左切换效果
    mySwiper.swipePrev();
  })
  //	右边箭头
  $div.find('.swiper-button-next').click(function () {
    mySwiper.swipeNext();
  })
}
//ec.product.scroll("pro-relation-scroll",4);
//ec.product.scroll("pro-hot-scroll",5);
//window.onload = function () {
//
//}
